将NSString拆分为Objective-C中的数组

时间:2012-02-05 17:33:50

标签: objective-c cocoa-touch nsstring nsarray

如何将字符串@"Hello"拆分为:

  • 'H''e''l''l''o'
  • 的C数组

或:

  • @[@"H", @"e", @"l", @"l", @"o"]
  • 的Objective-C数组

4 个答案:

答案 0 :(得分:33)

如果您对char的C数组感到满意,请尝试:

const char *array = [@"Hello" UTF8String];

如果您需要NSArray,请尝试:

NSMutableArray *array = [NSMutableArray array];
NSString *str = @"Hello";
for (int i = 0; i < [str length]; i++) {
    NSString *ch = [str substringWithRange:NSMakeRange(i, 1)];
    [array addObject:ch];
}

array将每个字符都包含在其中。

答案 1 :(得分:7)

试试这个:

- (void) testCode
{
    NSString *tempDigit = @"12345abcd" ;
    NSMutableArray *tempArray = [NSMutableArray array];
    [tempDigit enumerateSubstringsInRange:[tempDigit rangeOfString:tempDigit]
                                  options:NSStringEnumerationByComposedCharacterSequences
                               usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
            [tempArray addObject:substring] ;
        }] ;

    NSLog(@"tempArray = %@" , tempArray);
}

答案 2 :(得分:4)

您可以使用- (unichar)characterAtIndex:(NSUInteger)index访问每个索引处的字符串字符。

所以,

NSString* stringie = @"astring";
NSUInteger length = [stringie length];
unichar stringieChars[length];
for( unsigned int pos = 0 ; pos < length ; ++pos )
{
    stringieChars[pos] = [stringie characterAtIndex:pos];
}
// replace the 4th element of stringieChars with an 'a' character
stringieChars[3] = 'a';
// print the modified array you produced from the NSString*
NSLog(@"%@",[NSString stringWithCharacters:stringieChars length:length]);

答案 3 :(得分:0)

用户529758提到,拆分你的字符串 - C方式 - 如:

const char *array = [@"Hello" UTF8String];

但是然后使用:

循环它
for (int i = 0; i < sizeof(array); i++) {
  doSomethingWithCharacter(array[i]);
}