Split an NSString into an array in Objective-C

前端 未结 4 615
傲寒
傲寒 2021-02-05 14:23

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

  • a C array of \'H\', \'e\', \'l\', \'l\', \'
4条回答
  •  伪装坚强ぢ
    2021-02-05 14:33

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

提交回复
热议问题