How do I split a string with special characters into a NSMutableArray

随声附和 提交于 2019-12-05 15:41:56

First of all, your code is incorrect. characterAtIndex returns unichar, so you should use @"%C"(uppercase) as the format specifier.

Even with the correct format specifier, your code is unsafe, and strictly speaking, still incorrect, because not all unicode characters can be represented by a single unichar. You should always handle unicode strings per substring:

It's common to think of a string as a sequence of characters, but when working with NSString objects, or with Unicode strings in general, in most cases it is better to deal with substrings rather than with individual characters. The reason for this is that what the user perceives as a character in text may in many cases be represented by multiple characters in the string.

You should definitely read String Programming Guide.

Finally, the correct code for you:

NSString *danishString = @"æøå";
NSMutableArray *characters = [[NSMutableArray alloc] initWithCapacity:[danishString length]]; 
[danishString enumerateSubstringsInRange:NSMakeRange(0, danishString.length) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
    [characters addObject:substring];
}];

If with NSLog(@"%@", characters); you see "strange character" of the form "\Uxxxx", that's correct. It's the default stringification behavior of NSArray by description method. You can print these unicode characters one by one if you want to see the "normal characters":

for (NSString *c in characters) {
    NSLog(@"%@", c);
}

In your example, ichar isn't type of NSString, but unichar. If you want NSStrings try getting a substring instead :

NSString *danishString = @"æøå";
NSMutableArray *characters = [[NSMutableArray alloc] initWithCapacity:[danishString length]]; 

for (int i=0; i < [danishString length]; i++) 
{ 
    NSRange r = NSMakeRange(i, 1);
    NSString *ichar = [danishString substringWithRange:r]; 
    [characters addObject:ichar]; 
}

You could do something like the following, which should be fine with Danish characters, but would break down if you have decomposed characters. I suggest reading the String Programming Guide for more information.

NSString *danishString = @"æøå";
NSMutableArray* characters = [NSMutableArray array];
for( int i = 0; i < [danishString length]; i++ ) {
  NSString* subchar = [danishString substringWithRange:NSMakeRange(i, 1)];
  if( subchar ) [characters addObject:subchar];
}

That would split the string into an array of individual characters, assuming that all the code points were composed characters.

It is printing the unicode of the characters. Anyhow, you can use the unicode (with \u) anywhere.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!