user393273
user393273

Reputation: 1438

Split one string into different strings

i have the text in a string as shown below

011597464952,01521545545,454545474,454545444|Hello this is were the message is.

Basically i would like each of the numbers in different strings to the message eg

NSString *Number1 = 011597464952 
NSString *Number2 = 01521545545
etc
etc
NSString *Message = Hello this is were the message is.

i would like to have that split out from one string that contains it all

Upvotes: 16

Views: 27474

Answers (5)

Barry Wark
Barry Wark

Reputation: 107754

I would use -[NSString componentsSeparatedByString]:

NSString *str = @"011597464952,01521545545,454545474,454545444|Hello this is were the message is.";

NSArray *firstSplit = [str componentsSeparatedByString:@"|"];
NSAssert(firstSplit.count == 2, @"Oops! Parsed string had more than one |, no message or no numbers.");
NSString *msg = [firstSplit lastObject];
NSArray *numbers = [[firstSplit objectAtIndex:0] componentsSepratedByString:@","];

// print out the numbers (as strings)
for(NSString *currentNumberString in numbers) {
  NSLog(@"Number: %@", currentNumberString);
}

Upvotes: 45

Wasseem Khayrattee
Wasseem Khayrattee

Reputation: 682

Here's a handy function I use:

///Return an ARRAY containing the exploded chunk of strings
///@author: khayrattee
///@uri: http://7php.com
+(NSArray*)explodeString:(NSString*)stringToBeExploded WithDelimiter:(NSString*)delimiter
{
    return [stringToBeExploded componentsSeparatedByString: delimiter];
}

Upvotes: 0

falconcreek
falconcreek

Reputation: 4170

NSMutableArray *strings = [[@"011597464952,01521545545,454545474,454545444|Hello this is were the message is." componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@",|"]] mutableCopy];

NString *message = [[strings lastObject] copy];
[strings removeLastObject];

// strings now contains just the number strings
// do what you need to do strings and message

....

[strings release];
[message release];

Upvotes: 1

Eric
Eric

Reputation: 3895

Look at NSString componentsSeparatedByString or one of the similar APIs.

If this is a known fixed set of results, you can then take the resulting array and use it something like:

NSString *number1 = [array objectAtIndex:0];    
NSString *number2 = [array objectAtIndex:1];
...

If it is variable, look at the NSArray APIs and the objectEnumerator option.

Upvotes: 5

AShelly
AShelly

Reputation: 35520

does objective-c have strtok()?

The strtok function splits a string into substrings based on a set of delimiters. Each subsequent call gives the next substring.

substr = strtok(original, ",|");
while (substr!=NULL)
{
   output[i++]=substr;
   substr=strtok(NULL, ",|")
}

Upvotes: 0

Related Questions