我想要改组包含希腊字符的字符串:
这是我的代码:
- (void)shuffle {
NSLog(@"Will shuffle :%@",anagram2);
NSData* data = [anagram2 dataUsingEncoding:NSWindowsCP1253StringEncoding];
NSLog(@"after encoding :%@",anagram2);
NSString *someString = [[NSString alloc]initWithData:data encoding:NSWindowsCP1253StringEncoding];
NSLog(@"Greek word:%@",someString);
int length = anagram2.length;
NSMutableArray *letters = [[NSMutableArray alloc] init];
for (int i = 0; i< length; i++) {
NSString *letter = [NSString stringWithFormat:@"%c", [someString characterAtIndex:i]];
NSLog(@"Character:%@",letter);
[letters addObject:someLetter];
}
for (int i = 0; i<length; i++) {
int value = arc4random() % (length-1);
//NSLog(@"Value is : %i", value);
[letters exchangeObjectAtIndex:i withObjectAtIndex:value];
}
}
我可以正确地看到希腊词。但洗牌不起作用。如何提取每个字符并将其添加到字母数组中。它适用于英语单词,但不适用于希腊单词,所以我想我应该替换它:
NSString *letter = [NSString stringWithFormat:@"%c", [someString characterAtIndex:i]];
用别的东西。
答案 0 :(得分:2)
在我看来,主要问题是
[NSString stringWithFormat:@"%c":...]
仅适用于ASCII字符。您必须至少使用"%C"
格式
它适用于Unicode字符。
此外,只要您拥有指定编码中不可用的任何字符,从NSString
到NSData
的转换就会失败。
以下方法可以避免所有这些问题,并且可以使用任意Unicode字符 (即使使用Emojis,内部表示为2个UTF-16字符):
NSString *string = @"Ελλάδα ";
NSLog(@"Will shuffle: %@", string);
// Convert string to an array of (32 bit) Unicode characters:
NSMutableData *data = [[string dataUsingEncoding:NSUTF32BigEndianStringEncoding] mutableCopy];
uint32_t *letters = [data mutableBytes];
int length = [data length]/4; // The number of 32-bit Unicode characters
// Shuffle the Unicode characters:
for (int i = 0; i<length; i++) {
int value = arc4random() % (length-1);
uint32_t tmp = letters[i];
letters[i] = letters[value];
letters[value] = tmp;
}
// Create new string from the shuffled Unicode characters:
NSString *shuffled = [[NSString alloc] initWithData:data encoding:NSUTF32BigEndianStringEncoding];
NSLog(@"Shuffled: %@", shuffled);
输出:
Will shuffle: Ελλάδα Shuffled: αάλλ Εδ