How to get single characters from a string in ios for Gujrati language (in another language)

I am trying to get single characters from an NSString , for example "ઐતિહાસિક", "પ્રકાશન", "ક્રોધ" . I want an output like 1) ઐ, તિ, હા, સિ, ક 2) પ્ર, કા, શ, ન 3) ક્રો, ધ , but the output is as follows: 1) ઐ, ત, િ, હ, િ, ક 2) પ, ્, ર, ક, ા, શ, ન 3) ક, ્, ર, ો, ધ

I used the code as shown below:

 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); 

Take strElement as "ક્રોધ", then we get the output ક , ્ , ર , ો , ધ But I need a conclusion like this ક્રો,ધ

Is there any way to get the desired result? Any method available directly in iOS, or creating it yourself, and then in any way or idea, how to create it?

Any help is appreciated

+6
source share
1 answer

Your code assumes that each character in a string is a single unichar value. But this is not so. Some Unicode characters consist of several unichar values.

The solution is to use rangeOfComposedCharacterSequenceAtIndex: instead of substringWithRange: with a fixed range length of 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); 

It is output:

Results: ઐ, તિ, હા, સિ, ક, પ્ર, કા, શ, ન, ક્રો, ધ

+6
source

All Articles