我试图从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中可用的方法或需要由我自己创建它然后以任何方式或想法如何创建它?
任何帮助表示赞赏
解决方法
@H_403_16@ 您的代码假设字符串中的每个字符都是单个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);
这输出:
Results: ઐ,પ્ર,ન,ક્રો,ધ