我想转换NSString(ex. @"HELLO")
为NSArray(ex. [@"H", @"E", @"L", @"L", @"O", nil])
.
首先,我尝试使用componentsSeparatedByString
. 但它需要指示分隔符,所以我不能。我怎样才能做到这一点?
我想转换NSString(ex. @"HELLO")
为NSArray(ex. [@"H", @"E", @"L", @"L", @"O", nil])
.
首先,我尝试使用componentsSeparatedByString
. 但它需要指示分隔符,所以我不能。我怎样才能做到这一点?
将字符串拆分为数组的正确方法是执行以下操作(作为NSString
类别方法):
@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);
\U10000
如果字符串包含 Unicode 字符或更高版本,硬编码范围长度为 1 的解决方案将失败。这包括表情符号字符以及许多其他字符。
这是我的代码:
@interface NSString (ConvertToArray)
-(NSArray *)convertToArray;
@end
@implementation NSString (ConvertToArray)
-(NSArray *)convertToArray
{
NSMutableArray *arr = [[NSMutableArray alloc]init];
for (int i=0; i < self.length; i++) {
NSString *tmp_str = [self substringWithRange:NSMakeRange(i, 1)];
[arr addObject:[tmp_str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
}
return arr;
}
@end
:
- (void)foo
{
NSString *exString = @"HELLO";
NSArray *arr = [exString convertToArray];
for (NSString *str in arr) {
NSLog(@"%@\n",str);
}
}
NSString *string = @"HELLO";
NSMutableArray *array = [[NSMutableArray alloc] init];
for (int i = 0; i < string.length; i ++) {
[array addObject:[NSString stringWithFormat:@"%c", [string characterAtIndex:i]]];
}