4

我想转换NSString(ex. @"HELLO")NSArray(ex. [@"H", @"E", @"L", @"L", @"O", nil]).

首先,我尝试使用componentsSeparatedByString. 但它需要指示分隔符,所以我不能。我怎样才能做到这一点?

4

3 回答 3

7

将字符串拆分为数组的正确方法是执行以下操作(作为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 的解决方案将失败。这包括表情符号字符以及许多其他字符。

于 2013-04-09T00:38:55.773 回答
6

这是我的代码:

@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);
    }
}
于 2013-04-08T23:40:00.733 回答
2
NSString *string = @"HELLO";
NSMutableArray *array = [[NSMutableArray alloc] init];
for (int i = 0; i < string.length; i ++) {
    [array addObject:[NSString stringWithFormat:@"%c", [string characterAtIndex:i]]];
}
于 2013-04-08T23:35:34.237 回答