Split an NSString into an array in Objective-C

21,229

Solution 1

Try this :

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

Solution 2

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]);
Share:
21,229
ytpm
Author by

ytpm

Just another one.

Updated on July 19, 2020

Comments

  • ytpm
    ytpm almost 4 years

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

    • a C array of 'H', 'e', 'l', 'l', 'o'

    or:

    • an Objective-C array of @[@"H", @"e", @"l", @"l", @"o"]
  • ytpm
    ytpm over 12 years
    is there a command to replace a letter in array? like [array replaceObjectAtIndex:0] hah, something like that? if i want to replace something in array index?
  • Thomson Comer
    Thomson Comer over 12 years
    Now you've got a basic C array that you can make changes to index by index. I changed my answer to reflect your added question.
  • LenArt
    LenArt almost 10 years
    remember that const char *array from strings may end with the NUL character for terminating strings '\0', so your size may be 1 larger than the amount of readable characters. en.wikipedia.org/wiki/Ascii#ASCII_control_code_chart
  • Kyle Howells
    Kyle Howells about 8 years
    Upvote for being UTF8 aware and keeping multi byte characters (emoji, åccented characters) together.