在Objective-C中将NSString拆分成一个数组

如何将string@“Hello”拆分为数组item0:“H”,item1:“e”,item2:“l”,item3:“l”,item4:“o”。 我到处search,但无法find如何.. 🙁

哦,在Objective-C当然。

谢谢你的帮助。

如果你对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将包含每个字符作为它的一个元素。

尝试这个 :

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

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

所以,

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

一个user529758提到,分割你的string – C的方式 – 就像:

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

但是,然后使用循环:

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