【问题标题】:Split an NSString into an array in Objective-C在 Objective-C 中将 NSString 拆分为数组
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • 是否有替换数组中字母的命令?像 [array replaceObjectAtIndex:0] 哈哈,类似的东西?如果我想替换数组索引中的某些内容?
  • @H2CO3 不要使用范围为 1 的子字符串,只需使用 -characterAtIndex:
  • 那么如何将非对象 `char' 添加到数组中?
  • for (int i; i &lt; sizeof(array); i++) { doSomethingWith(array[i]); }循环你的const char *array
【解决方案2】:

试试这个:

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

【讨论】:

  • 赞成支持 UTF8 并将多字节字符(表情符号、重音字符)放在一起。
【解决方案3】:

您可以使用- (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]);

【讨论】:

  • 有替换数组中字母的命令吗?像 [array replaceObjectAtIndex:0] 哈,类似的东西?如果我想替换数组索引中的某些内容?
  • 现在您已经有了一个基本的 C 数组,您可以按索引对索引进行更改。我更改了答案以反映您添加的问题。
【解决方案4】:

A user529758 提到,拆分你的字符串 - C 方式 - 就像:

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

然后循环使用:

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-18
  • 2020-10-26
  • 2016-12-17
相关资源
最近更新 更多