我该如何将字符串@"Hello"
分割为以下两种形式之一:
- C数组:
'H'
,'e'
,'l'
,'l'
,'o'
或者:
- Objective-C数组:
@[@"H", @"e", @"l", @"l", @"o"]
我该如何将字符串@"Hello"
分割为以下两种形式之一:
'H'
, 'e'
, 'l'
, 'l'
, 'o'
或者:
@[@"H", @"e", @"l", @"l", @"o"]
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:
代替使用范围为1的子字符串。 - Jack Lawrencechar
添加到数组中? - user529758const char *array
数组:for (int i; i < sizeof(array); i++) { doSomethingWith(array[i]); }
- LenArt试试看:
- (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]);
const char *array = [@"Hello" UTF8String];
然后使用循环来执行:
for (int i = 0; i < sizeof(array); i++) {
doSomethingWithCharacter(array[i]);
}
const char *array
可能以终止字符串的 NUL 字符 '\0'
结尾,因此您的大小可能比可读字符的数量大 1。http://en.wikipedia.org/wiki/Ascii#ASCII_control_code_chart - LenArt