Split an NSString into an array in Objective-C

醉酒当歌 提交于 2019-12-20 12:34:38

问题


How can I split the string @"Hello" to either:

  • a C array of 'H', 'e', 'l', 'l', 'o'

or:

  • an Objective-C array of @[@"H", @"e", @"l", @"l", @"o"]

回答1:


If you're satisfied with a C array of chars, try:

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

If you need an NSArray, try:

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];
}

And array will contain each character as an element of it.




回答2:


Try this :

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



回答3:


You can use - (unichar)characterAtIndex:(NSUInteger)index to access the string characters at each index.

So,

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



回答4:


A user529758 mentions, split your string - the C way - like:

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

But then loop it using:

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


来源:https://stackoverflow.com/questions/9151363/split-an-nsstring-into-an-array-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!