[NSString rangeOfComposedCharacterSequenceAtIndex]
Returns the range in the receiver of the composed character sequence located at a given index.
- (NSRange)rangeOfComposedCharacterSequenceAtIndex:(NSUInteger)anIndex
Parameters
- anIndex
- The index of a character in the receiver. The value must not exceed the bounds of the receiver.
Return Value of [NSString rangeOfComposedCharacterSequenceAtIndex]
The range in the receiver of the composed character sequence located at anIndex.
Discussion
The composed character sequence includes the first base character found at or before anIndex, and its length includes the base character and all non-base characters following the base character.
Example of [NSString rangeOfComposedCharacterSequenceAtIndex]
@interface NSString (UTF)
- (NSRange) rangeOfUTFCodePoint:(NSUInteger)number;
@end
@implementation NSString (UTF)
- (NSRange) rangeOfUTFCodePoint:(NSUInteger)number
{
NSUInteger codeUnit = 0;
NSRange result;
for(NSUInteger ix = 0; ix <= number; ix++)
{
result = [self rangeOfComposedCharacterSequenceAtIndex:codeUnit];
codeUnit += result.length;
}
return result;
}
@end
Example of [NSString rangeOfComposedCharacterSequenceAtIndex]
@interface NSString (ConvertToArray)
-(NSArray *)convertToArray;
@end
@implementation NSString (ConvertToArray)
- (NSArray *)convertToArray {
NSMutableArray *arr = [[NSMutableArray alloc] init];
NSUInteger i = 0;
while (i < self.length) {
NSRange range = [self rangeOfComposedCharacterSequenceAtIndex:i];
NSString *chStr = [self substringWithRange:range];
[arr addObject:chStr];
i += range.length;
}
return arr;
}
@end
NSArray *array = [@"Hello 😄" convertToArray];
NSLog(@"array = %@", array);
Example of [NSString rangeOfComposedCharacterSequenceAtIndex]
NSUInteger lastCharIndex = [myString length] - 1; // I assume string is not empty
NSRange rangeOfLastChar = [myString rangeOfComposedCharacterSequenceAtIndex: lastCharIndex];
myNewString = [myString substringToIndex: rangeOfLastChar.location];