Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 238
user393273 Avatar asked Aug 12 '10 18:08

user393273


People also ask

Can a string be divided?

String split is used to break the string into chunks. Python provides an in-built method called split() for string splitting. We can access the split string by using list or Arrays. String split is commonly used to extract a specific value or text from the given string.

How would you read a string and split it into substring?

Use the Split method when the substrings you want are separated by a known delimiting character (or characters). Regular expressions are useful when the string conforms to a fixed pattern. Use the IndexOf and Substring methods in conjunction when you don't want to extract all of the substrings in a string.

How do you extract part of a string?

The substr() method extracts a part of a string. The substr() method begins at a specified position, and returns a specified number of characters. The substr() method does not change the original string. To extract characters from the end of the string, use a negative start position.

How do you split a string into two strings in Python?

Use Split () Function This function splits the string into smaller sections. This is the opposite of merging many strings into one. The split () function contains two parameters. In the first parameter, we pass the symbol that is used for the split.


Video Answer


2 Answers

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);
}
like image 113
Barry Wark Avatar answered Sep 19 '22 16:09

Barry Wark


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.

like image 45
Eric Avatar answered Sep 19 '22 16:09

Eric