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]);
Comments
-
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"]
- a C array of
-
ytpm over 12 yearsis 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 over 12 yearsNow 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 almost 10 yearsremember 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 about 8 yearsUpvote for being UTF8 aware and keeping multi byte characters (emoji, åccented characters) together.