Split one string into different strings - iphone

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

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);
}

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.

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];

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, ",|")
}

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];
}

Related

Read from txt list file and set many objects in ios

I, I'm writing an application that has to read the content of txt.
this txt is such a property file with a list formatted in this way:
1|Chapter 1|30
2|Chapter AA|7
3|Story of the United States|13
........
keys are separated by "|".
I googled a lot hoping to find any "pragmatically solution" but nothing...
how can I read these informations and set many objects like:
for NSInterger *nChapter = the first element
for NSString *title = the second element
for NSInteger *nOfPages = the last element ?
NSString's - (NSArray *)componentsSeparatedByString:(NSString *)separator could be your best friend.
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/doc/uid/20000154-componentsSeparatedByString_
Only if you read NSString's class reference:
NSString *str = [NSString stringWithContentsOfFile:#"file.txt"];
NSArray *rows = [str componentsSeparatedByString:#"\n"];
for (NSString *row in rows)
{
NSArray *fields = [row componentsSeparatedByString:#"|"];
NSInteger nChapter = [[fields objectAtIndex:0] intValue];
NSString *title = [fields objectAtIndex:1];
// process them in here
}

How to create a comma-separated string?

I want to create a comma-separated string like this.
NSString *list = #"iPhone,iPad,iPod";
I tried like this,
[strItemList appendString:[NSString stringWithFormat:#"%#,", [[arrItems objectAtIndex:i]objectForKey:#"ItemList"]]];
But the issue is I'm getting a string like this
#"iPhone,iPad,iPod," Note that there is an extra comma "," at the end of the string. How can I avoid that extra comma?
Can you please give me a hint. Highly appreciated
Thanks in advance
To join an array of strings into a single string by a separator (character which would be a string), you could use this method of NSArray class:
NSArray* array = #[#"iPhone", #"iPad", #"iPod"];
NSString* query = [array componentsJoinedByString:#","];
By using this method, you won't need to drop the last extra comma (or whatever) because it won't add it to the final string.
There's a couple of routes you can take.
If the number of items is always the same, and known before hand (which I guess isn't the case, but I mention it for completeness's sake), just make the whole string at once:
[NSString stringWithFormat:#"%#,%#,%#", [[arrItems objectAtIndex:0] objectForKey:#"ItemList"]], [[arrItems objectAtIndex:1] objectForKey:#"ItemList"]], [[arrItems objectAtIndex:2] objectForKey:#"ItemList"]]
Knowing that the unwanted comma will always be the last character in the string, you can make removing it the last step in construction:
} // End of loop
[strItemList removeCharactersInRange:(NSRange){[strItemList length] - 1, 1}];
Or you can change your thinking a little and do the loop like this:
NSString * comma = #"";
for( i = 0; i < [arrItems count]; i++ ){
[strItemList appendString:[NSString stringWithFormat:#"%#%#", comma, [[arrItems objectAtIndex:i]objectForKey:#"ItemList"]]];
comma = #",";
}
Notice that comma comes before the other item. Setting that string inside the loop means that nothing will be added on the first item, but a comma character will be for every other item.
After Completion of loop add below stmt
strItemList = [strItemList substringToIndex:[strItemList length]-1]
check the value of array count if array count is last then add without comma else add with comma. try this out i am not sure to much about.
if([arrItems objectAtIndex:i] == arrItems.count){
[strItemList appendString:[NSString stringWithFormat:#"%#", [[arrItems objectAtIndex:i]objectForKey:#"ItemList"]]];
}
else {
[strItemList appendString:[NSString stringWithFormat:#"%#,", [[arrItems objectAtIndex:i]objectForKey:#"ItemList"]]];
}
Assuming that arrItems is an NSArray with elements #"iPhone", #"iPad", and #"iPod", you can do this:
NSArray *list = [arrItems componentsJoinedByString:#","]
NSArray with elements #"iPhone", #"iPad", and #"iPod"
NSString *str=[[arrItems objectAtIndex:0]objectForKey:#"ItemList"]]
str = [str stringByAppendingFormat:#",%#",[[arrItems objectAtIndex:1]objectForKey:#"ItemList"]]];
str = [str stringByAppendingFormat:#",%#",[[arrItems objectAtIndex:2]objectForKey:#"ItemList"]]];
NsLog(#"%#",str);
// Assuming...
NSDictionary *dictionary1 = [NSDictionary dictionaryWithObject:[NSArray arrayWithObjects:#"iPhone", #"iPodTouch", nil] forKey:#"ItemList"];
NSDictionary *dictionary2 = [NSDictionary dictionaryWithObject:[NSArray arrayWithObjects:#"iPad", #"iPad2", #"Apple TV", nil] forKey:#"ItemList"];
NSDictionary *dictionary3 = [NSDictionary dictionaryWithObject:[NSArray arrayWithObjects:#"iMac", #"MacBook Pro", #"Mac Pro", nil] forKey:#"ItemList"];
NSArray *arrItems = [NSArray arrayWithObjects:dictionary1, dictionary2, dictionary3, nil];
// create string list
NSString *strItemList = [[arrItems valueForKeyPath:#"#unionOfArrays.ItemList"] componentsJoinedByString:#", "];
NSLog(#"All Items List: %#", strItemList);
Output:
All Items List: iPhone, iPodTouch, iPad, iPad2, Apple TV, iMac, MacBook Pro, Mac Pro
This method will return you the nsmutablestring with comma separated values from an array
-(NSMutableString *)strMutableFromArray:(NSMutableArray *)arr withSeperater:(NSString *)saperator
{
NSMutableString *strResult = [NSMutableString string];
for (int j=0; j<[arr count]; j++)
{
NSString *strBar = [arr objectAtIndex:j];
[strResult appendString:[NSString stringWithFormat:#"%#",strBar]];
if (j != [arr count]-1)
{
[strResult appendString:[NSString stringWithFormat:#"%#",seperator]];
}
}
return strResult;
}

Is it possible to get an array to show up as text?

I'm trying to do something like this ..
NSString *string = [NSString stringWithFormat:#"Hello World"];
NSArray *array = [NSArray arrayWithObject:string];
[uitextviewOutlet setText:[NSArray arrayWithArray:array]];
and I'd like for that to show up on my uitextviewOutlet window, which is an object of UITextView that will print out text.
The code works if I straight out send the uitextviewOutlet object the setText message and if it takes string as the parameter, but it won't take the array.
is there a way to have it take an array?
TIA.
You can join the elements with, let's say a comma like this: NSString *joinedString = [array1 componentsJoinedByString:#","];
Edit_: I'm not a friend of "Do it for me", but here you go:
NSString *string = [NSString stringWithFormat:#"Hello World"];
NSArray *array = [NSArray arrayWithObject:string];
[uitextviewOutlet setText:[array componentsJoinedByString:#","]];
By the way, your code makes no sense, or do you fill up the array with more than just one value?
You can convert an array to a string with -componentsJoinedByString: as in #BjörnKaiser`s example. Or for more flexibility you can do:
NSString *string = [NSString stringWithFormat:#"Hello World"];
NSArray *array = [NSArray arrayWithObject:string];
for (NSString *araryItem in array) {
[uitextviewOutlet replaceRange:NSMakeRange(uitextviewOutlet.text.length, 0) withText:#"foo\n"];
[uitextviewOutlet replaceRange:NSMakeRange(uitextviewOutlet.text.length, 0) withText:arrayItem];
}

NSRegularExpression to extract text

All,
I have a dictionary with two keys and values. I need to extract bits and pieces from them and place them into seperate strings.
{
IP = "192.168.17.1";
desc = "VUWI-VUWI-ABC_Dry_Cleaning-R12-01";
}
That is what the dictionary looks like when I call description.
I want the new output to be like this:
NSString *IP = #"192.168.17.1";
NSString *desc = #"ABC Dry Cleaning"; //note: I need to get rid of the underscores
NSString *type = #"R";
NSString *num = #"12";
NSString *ident = #"01";
How would I achieve this?
I've read through the Apple developer docs on NSRegularExpression but I find it hard to understand. I'm sure once I get some help once here I can figure it out in the future, I just need to get started.
Thanks in advance.
Okay, so first, you have to get the object associated with each key:
NSString *ip = [dic objectForKey:#"IP"]; //Btw, you shouldn't start a variable's name with a capital letter.
NSString *tempDesc = [dic objectForKey:#"desc"];
Then, what I would do is split the string in tempDesc, based on the character -.
NSArray *tmpArray = [tempDesc componentsSeparatedByString:#"-"];
Then you just have to get the strings or substrings you're interested in, and reformat them as needed:
NSString *desc = [[tmpArray objectAtIndex:2] stringByReplacingOccurrencesOfString:#"_" withString:#" "];
NSString *type = [[tmpArray objectAtIndex:3] substringToIndex:1];
NSString *num = [[tmpArray objectAtIndex:3] substringFromIndex:1];
NSString *ident = [tmpArray objectAtIndex:4];
As you can see, this works perfectly without using NSRegularExpression.

how to concatenate values to the string

i want to cancatenate strings with comma as a separator and result must be stored in string...
comma=#",";
for(i=0;i<[resources count];i++)
{
Record *aRecord = [resources objectAtIndex:i];
temp=aRecord.programID;
if(i==0)
pid=temp;
else
//i am using this one to cancatenate but is not working why?
pid = [NSString stringWithFormat:#"%#%#%#", pid,comma,temp];
}
Use the -componentsJoinedByString: method on NSArray:
NSArray *csvArray = [NSArray arrayWithObjects:#"here", #"be", #"dragons", nil];
NSLog(#"%#", [csvArray componentsJoinedByString:#", "]);
(from the docs)
Cast the id types to NSString and then use the concatenation methods found in the class reference of NSString.