【发布时间】:2012-02-27 09:52:39
【问题描述】:
如何将字符串 @"Hello" 拆分为:
-
'H'、'e'、'l'、'l'、'o'的 C 数组
或:
-
@[@"H", @"e", @"l", @"l", @"o"]的 Objective-C 数组
【问题讨论】:
标签: objective-c cocoa-touch nsstring nsarray
如何将字符串 @"Hello" 拆分为:
'H'、'e'、'l'、'l'、'o' 的 C 数组
或:
@[@"H", @"e", @"l", @"l", @"o"] 的 Objective-C 数组
【问题讨论】:
标签: objective-c cocoa-touch nsstring nsarray
如果您对 chars 的 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 将包含每个字符作为它的一个元素。
【讨论】:
-characterAtIndex:。
for (int i; i < sizeof(array); i++) { doSomethingWith(array[i]); }循环你的const char *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 访问每个索引处的字符串字符。
所以,
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]);
【讨论】:
A user529758 提到,拆分你的字符串 - C 方式 - 就像:
const char *array = [@"Hello" UTF8String];
然后循环使用:
for (int i = 0; i < sizeof(array); i++) {
doSomethingWithCharacter(array[i]);
}
【讨论】:
const char *array 可能以NUL 字符结尾以终止字符串'\0',因此您的大小可能比可读字符的数量大1。 en.wikipedia.org/wiki/Ascii#ASCII_control_code_chart