how can I convert string to an array with separator?
12,945
Solution 1
componentsSeparatedByString:
splits the string and return the result in an array.
NSArray *myArray = [myString componentsSeparatedByString:@"+"];
[myArray objectAtIndex:0];//cat
[myArray objectAtIndex:1];//dog
[myArray objectAtIndex:2];//cow
Solution 2
Try this..
NSArray *arr = [myString componentsSeparatedByString:@"-"];
[arr objectAtIndex:0];//Hai
[arr objectAtIndex:1];//Welcome
Solution 3
Use the componentsSeparatedByString:
method of NSString.
NSString string = @"hai-welcome";
NSArray myArray = [string componentsSeparatedByString:@"-"];
NSString* haiString = [myArray objectAtIndex:0];
NSString* welcomeString = [myArray objectAtIndex:1];
Solution 4
It is vert simple..
NSString * test = @"Hello-hi-splitting-for-test";
NSArray * stringArray = [test componentsSeparatedByString:@"-"];
// Now stringArray will contain all splitted strings.. :)
Hope this helps...
I you don't want use array then iterate through each character...
NSMutableString * splittedString = nil;
for(int i=0;i<test.length;i++){
unichar character = [test characterAtIndex:0];
if (character=='-') {
if (splittedString!=nil) {
NSLog(@"String component %@",splittedString);
[splittedString release];
splittedString = nil;
}
} else {
if (splittedString==nil) {
splittedString = [[NSMutableString alloc] init];
}
[splittedString appendFormat:@"%C",character];
}
}
if (splittedString!=nil) {
NSLog(@"String last component %@",splittedString);
[splittedString release];
splittedString = nil;
}
Thats all...
Solution 5
NSArray *myWords = [myString componentsSeparatedByString:@"+"];
Author by
Vipin
Updated on June 05, 2022Comments
-
Vipin almost 2 years
I have a string in the following format
myString = "cat+dog+cow"
I need to store each string separated by + in to a array. Eg:
myArray[0] = cat myArray[1] = dog myArray[2] = cow
Can anyone tell me the proper way to do this?