views:

375

answers:

4

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

A: 

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, ",|")
}
AShelly
No, but C does, and since Objective-C is a strict superset of C, Objective-C gets it for free.
Allyn
Can you explain please :)
i do not think that this will work on objective c
You can use `strtok` in Objective-C (it is a superset of C), but `strtok` expects C-style strings. `NSString` is not the same beast at all. It is a unicode string. Although you can get a C-style string (given an encoding), I wouldn't go down this route.
Barry Wark
It would, but you'd have to use C strings.
Allyn
+2  A: 

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.

Eric
yeah I found that earlier but how do i put each array into a separate string ?
Added a little more detail to the original post.
Eric
+3  A: 

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 number) {
  NSLog(@"Number: %@", currentNumberString);
}
Barry Wark
A: 
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];
falconcreek