我正在尝试从NSString
获取单个字符,例如“ઐતિહાસિક”,“પ્રકાશન”,“ક્રોધ”。我希望输出像 1)ઐ,તિ,હા,સિ,ક2)પ્ર,કા,શ,ન3)ક્રો,ધ,但输出就像这样 1)ઐ, ત,િ,હ,િ,ક2)પ,્,ર,ક,ા,શ,ન3)ક,્,ર,ો,ધ
我使用了以下代码:
NSMutableArray *array = [[NSMutableArray alloc]init];
for (int i=0; i<strElement.length; i++)
{
NSString *str = [strElement substringWithRange:NSMakeRange(i, 1)];
[array addObject:str];
}
NSLog(@"%@",array);
让我们将strElement
作为“ક્રોધ”然后我得到这样的输出ક , ્ , ર , ો , ધ
但我需要像ક્રો,ધ
有什么方法可以获得所需的输出吗?任何直接在iOS中可用的方法或需要由我自己创建它然后以任何方式或想法如何创建它?
感谢任何帮助
答案 0 :(得分:7)
您的代码假设字符串中的每个字符都是单个unichar
值。但事实并非如此。某些Unicode字符由多个unichar
值组成。
解决方案是使用rangeOfComposedCharacterSequenceAtIndex:
代替substringWithRange:
,固定范围长度为1.
NSString *strElement = @"ઐતિહાસિક પ્રકાશન ક્રોધ";
NSMutableArray *array = [[NSMutableArray alloc]init];
NSInteger i = 0;
while (i < strElement.length) {
NSRange range = [strElement rangeOfComposedCharacterSequenceAtIndex:i];
NSString *str = [strElement substringWithRange:range];
[array addObject:str];
i = range.location + range.length;
}
// Log the results. Build the results into a mutable string to avoid
// the ugly Unicode escapes shown by simply logging the array.
NSMutableString *res = [NSMutableString string];
for (NSString *str in array) {
if (res.length) {
[res appendString:@", "];
}
[res appendString:str];
}
NSLog(@"Results: %@", res);
输出:
结果:ઐ,તિ,હા,સિ,ક,,પ્ર,કા,શ,ન,,ક્રો,ધ