how can I convert string to an array with separator? - iphone

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?

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

Try this..
NSArray *arr = [myString componentsSeparatedByString:#"-"];
[arr objectAtIndex:0];//Hai
[arr objectAtIndex:1];//Welcome

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...

NSArray *myWords = [myString componentsSeparatedByString:#"+"];

You can find this one very simple
NSString *str = #"cat+dog+cow";
NSArray *arr = [str componentsSeparatedByString:#"+"];
NSLog(#"Array items %#",arr);
OUTPUT:
Array items
(
Cat,
dog,
Cow
)

Use the componentsSeparatedByString: method of NSString.
NSString string = #"hai-welcome";
NSArray myArray = [string componentsSeparatedByString:#"-"];
NSString* haiString = [myArray objectAtIndex:0];
NSString* welcomeString = [myArray objectAtIndex:1];

NSArray *strArray = [myString componentsSeparatedByString:#"-"];
firstString = [strArray objectAtIndex:0];//Hai
secondString = [strArray objectAtIndex:1];//Welcome

This will be the solution if you are dealing with a string:
NSString *mySstring = #"hai-welcome";
NSMutableArray *anArray=[[NSMutableArray alloc] initWithArray:[componentsSeparatedByString: #"-"]];
And each word will be stored in respective position from 0-n.
Try This. :)

If you are averse to using arrays, you can consider this –
NSString *accessMode, *message;
NSScanner *scanner = [NSScanner scannerWithString:#"hai-welcome"];
NSCharacterSet *hyphenSet = [NSCharacterSet characterSetWithCharactersInString:#"-"];
[scanner scanUpToCharactersFromSet:hyphenSet intoString:&accessMode];
[scanner scanCharactersFromSet:hyphenSet intoString:nil];
[scanner scanUpToCharactersFromSet:[NSCharacterSet characterSetWithCharactersInString:#""] intoString:&message];

NSArray *lines = [string componentsSeparatedByString:#"-"];
The first value will be stored in 0th index of lines and second value will be stored in 1th index of lines..
Why not array?

Simple code :
NSString *myString = [[NSString alloc] initWithString:#"cat+dog+cow"];
NSArray *resultArray = [tempString componentsSeparatedByString:#"+"];
NSLog(#"1. %# 2. %# 3. %#",[resultArray objectAtIndex:0],[resultArray objectAtIndex:1],[resultArray objectAtIndex:2]);

Try This:
NSString *str = #"cat+dog+cow" ;
NSArray *array = [str componentsSeparatedByString:#"+"];
NSLog(#"%#",array) ;

Related

Convert NSString to NSDictionary separated by specific character

I need to convert this "5?8?519223cef9cee4df999436c5e8f3e96a?EVAL_TIME?60?2013-03-21" string into dictionary. Separated by "?"
Dictionary would be some thing like
{
sometext1 = "5",
sometext2 = "8",
sometext3 = "519223cef9cee4df999436c5e8f3e96a",
sometext4 = "EVAL_TIME",
sometext5 = "60",
sometext6 = "2013-03-21"
}
Thank you .
Break the string to smaller strings and loop for them.
This is the way
NSArray *objects = [inputString componentsSeparatedByString:#"?"];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
int i = 1;
for (NSString *str in objects)
{
[dict setObject:str forKey:[NSString stringWithFormat:#"sometext%d", i++]];
}
Try
NSString *string = #"5?8?3519223cef9cee4df999436c5e8f3e96a?EVAL_TIME?60?2013-03-21";
NSArray *stringComponents = [string componentsSeparatedByString:#"?"];
//This is very risky, your code is at the mercy of the input string
NSArray *keys = #[#"cid",#"avid",#"sid",#"TLicense",#"LLicense",#"date"];
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
for (int idx = 0; idx<[stringComponents count]; idx++) {
NSString *value = stringComponents[idx];
NSString *key = keys[idx];
[dictionary setObject:value forKey:key];
}
EDIT: More optimized
NSString *string = #"5?8?3519223cef9cee4df999436c5e8f3e96a?EVAL_TIME?60?2013-03-21";
NSArray *stringComponents = [string componentsSeparatedByString:#"?"];
NSArray *keys = #[#"cid",#"avid",#"sid",#"TLicense",#"LLicense",#"date"];
NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithObjects:stringComponents forKeys:keys];
first separate the string into several arrays by '?'.
then add the string in you dictionary.
sth like this:
NSString *str = #"5?8?519223cef9cee4df999436c5e8f3e96a?EVAL_TIME?60?2013-03-21";
NSArray *valueArray = [str componentsSeparatedByString:#"?"];
NSMutableArray *keyArray = [[NSMutableArray alloc] init];
for (int i = 0; i <[valueArray count]; i ++) {
[keyArray addObject:[NSString stringWithFormat:#"sometext%d",i+1]];
}
NSDictionary *dic = [[NSDictionary alloc] initWithObjects:valueArray forKeys:keyArray];
For the future: If you were to store your data in JSON format (closer to what you have anyway), it'll be much easier to deal with and transfer between systems. You can easily read it...using NSJSONSerialization

How to separate parts of NSString?

I have a NSMutableArray of NSStrings where each element of array has the format equal to #"key is 1::value is 1". Now I want to store string part coming before "::" in an array1 and string part coming after "::" in an array2. How can I do that?
Here is the Code :
NSArray *temp = [YourString componentsSeparatedByString:#"::"];
NSString *str1 = [temp objectAtIndex:0];
NSString *str2 = [temp objectAtIndex:1];
But prior to accessing the Objects in the Array .. check for whether it contains the value.
Try this ::
NSString *s = #"key is 1::value is 1";
NSArray *a = [s componentsSeparatedByString:#"::"];
NSLog(#" -> %# --> %#", [a objectAtIndex:0], [a objectAtIndex:1]);
use this:
[array1 addObject:[[YourString componentsSeparatedByString:#"::"] objectAtIndex:0]];
[array2 addObject:[[YourString componentsSeparatedByString:#"::"] objectAtIndex:1]];
The key to splitting your strings is to use the componentsSeparatedByString: method on NSString to separate your string into an NSArray. Read the docs on how this method acts with blank strings etc, but it's what you'd use.
You said you have an array of strings, so the basic implementation would involve iterating over that array and adding each element to the two other arrays.
NSMutableArray *arrayOfStrings = [NSMutableArray array];
NSMutableArray *array1 = [NSMutableArray array];
NSMutableArray *array2 = [NSMutableArray array];
for (NSString *string in arrayOfStrings)
{
NSArray *components = [string componentsSeparatedByString:#"::"];
if ([components count] == 2)
{
NSString *obj1 = [components objectAtIndex:0];
NSString *obj2 = [components objectAtIndex:1];
[array1 addObject:obj1];
[array2 addObject:obj2];
}
}
I found the way. I will keep adding the beforeString and afterString in array1 and array 2 respectively while iterating the elements of original array
for(int i=0;i<self.originalArray.count;i++)
{
NSString *temp=[self.originalArray objectAtIndex:i];
NSRange r = [temp rangeOfString:#"::"];
NSString *beforeString = [temp substringToIndex:r.location];
NSString *afterString = [temp substringFromIndex:r.location+2];
[array1 addObject:beforeString];
[array2 addObject:afterString];
}

How to find matching words in two separate strings?

If there are two separate strings, we need to retrieve all words that are matching (in those strings), in an array. also this matching should be case insensitive. What will be the most efficient way to achieve this.
For Example:
NSString *s1 = #"Hello there, I want to match similar words.";
NSString *s2 = #"Do you really want to match word, hello?";
The resulting array should contain, "hello", "want", "to", "match".
I went through many questions and, responses over the net like Regular expression to match a line that doesn't contain a word?, but didn't, find solution needed.
try this:
NSString *s1 = #"Hello there, I want to match similar words.";
NSString *s2 = #"Do you really Want to match word, hello?";
NSCharacterSet *separatorSet = [NSCharacterSet characterSetWithCharactersInString:#" ?.,"];
NSArray *as1 = [[s1 lowercaseString] componentsSeparatedByCharactersInSet:separatorSet];
NSArray *as2 = [[s2 lowercaseString] componentsSeparatedByCharactersInSet:separatorSet];
NSMutableSet* set1 = [NSMutableSet setWithArray:as1];
NSMutableSet* set2 = [NSMutableSet setWithArray:as2];
[set1 intersectSet:set2];
[set1 removeObject:#""];
NSArray* result =[set1 allObjects];
NSLog(#"%#",result);
You can use NSMutableSet for this..
NSString *s1 = #"Hello there, I want to match similar words.";
NSString *s2 = #"Do you really want to match word, hello?";
NSArray *components = [s1 componentsSeparatedByString:#" "];
NSArray *components1 = [s2 componentsSeparatedByString:#" "];
NSLog(#"%#",components);
NSLog(#"%#",components1);
NSMutableSet *resultSet = [NSMutableSet setWithArray:components1];
NSSet *setA = [NSSet setWithArray:components];
[resultSet intersectSet:setA];
NSArray *result = [resultSet allObjects];
NSLog(#"%#",result);
This Solution will work for you, If you don't have any punctuations in the sentences.. If you want sentences with punctuations to work just remove all the punctuations in your sentences.
NSString *s1 = #"Hello there, I want to match similar words.";
NSString *s2 = #"Do you really want to match word, hello?";
NSCharacterSet *separatorSet = [NSCharacterSet characterSetWithCharactersInString:#" ?.,"];
NSArray *s1Array = [s1 componentsSeparatedByCharactersInSet:separatorSet];
NSArray *s2Array = [s2 componentsSeparatedByCharactersInSet:separatorSet];
NSMutableArray *resultArray = [NSMutableArray arrayWithCapacity:0];
for(int index = 0; index < [s1Array count]; index++){
NSString *compareString = [[s1Array objectAtIndex:index] lowercaseString];
NSUInteger findIndex = [s2Array indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
NSString *currentString = (NSString *)obj;
if([[currentString lowercaseString] isEqualToString:compareString] &&
![currentString isEqualToString:#""]){
return YES;
*stop = YES;
}else{
return NO;
}
}
];
if(findIndex !=NSNotFound){
[resultArray addObject:compareString];
}
}
NSLog(#"Result:%#",[resultArray description]);
Try with below code
NSString *s1 = #"Hello there, I want to match similar words.";
NSString *s2 = #"Do you really want to match word, hello?";
NSCharacterSet *doNotWant = [[NSCharacterSet letterCharacterSet] invertedSet];
NSArray *array1 = [[s1 uppercaseString] componentsSeparatedByCharactersInSet:doNotWant];
NSArray *array2 = [[s2 uppercaseString] componentsSeparatedByCharactersInSet:doNotWant];
NSSet *set1 = [[NSSet alloc] initWithArray:array1];
NSMutableSet *set2 = [[NSMutableSet alloc] initWithArray:array2];
[set2 intersectSet:set1];
NSLog(#"set2:%#",set2);
NSLog(#"set1:%#",set1);
NSArray *aray_res = [set2 allObjects];
NSLog(#"aray_res:%#",aray_res);

How to convert string to array in objective C?

How to convert string to array in objective C. i.e,I have a string,
NSString *str = #"Hi,How r u";
This should be converted into an array *NSMutableArray arr , where in
arr[0] = "Hi"
arr[1] = ","
arr[2] = "How"
arr[3] = "r"
arr[4] = "u"
Can anybody help with the idea to crack this thing.
NSString *str=#"Hi,How r u";
NSArray *arr = [str componentsSeparatedByString:#","];
NSString *strSecond = [arr objectAtIndex:1];
NSMutableArray *arrSecond = [strSecond componentsSeparatedByString:#" "];
NSString *strHow = [arr objectAtIndex:0];
NSString *strAre = [arr objectAtIndex:1];
NSString *strYou = [arr objectAtIndex:2];
[arr removeObjectAtIndex:1];
[arr addObject:#","];
[arr addObject:strHow];
[arr addObject:strAre];
[arr addObject:strYou];
arr is the desired array.
I guess this link will help you.
NSString *str = #"Hi,How r u";
NSArray *listItems = [str componentsSeparatedByString:#","];
You have to do,
NSString *str = #"Hi,How r u";
NSArray *arr = [str componentsSeparatedByString:#" "];
And, in order for this to work as you expect, there should be a white-space between "Hi," and "How". Your string should look like #"Hi, How r u".
try this
NSString *str2=#"Hi,How r u";
NSMutableArray *arary = [[NSMutableArray alloc] initWithArray:[str2 componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#", "]]];
NSLog(#"%#",arary);
if you want , as a object
NSString *str2=#"Hi,How r u";
str2 = [str2 stringByReplacingOccurrencesOfString:#"," withString:#" , "];
NSMutableArray *arary = [[NSMutableArray alloc] initWithArray:[str2 componentsSeparatedByString:#" "]];
NSLog(#"%#",arary);
You can use the NSString method componentsSeparatedByString. Take a look at the reference here.

iPhone:Convert NSString 123-123-1234 into (123) 123-1234

I have string like 123-123-1234 so I want to convert string into this format
(123) 123-1234 so any idea to develop this functionality.
Thanks in advance.
I think something like this:
NSString *list = #"123-123-1234";
NSArray *listItems = [list componentsSeparatedByString:#"-"];
NSString *result = [NSString stringWithFormat:#"(%#) %#-%#", [listItem objectAtIndex:0], [listItem objectAtIndex:1], [listItem objectAtIndex:2]];
NSString * original = #"123-123-1234";
NSArray * components = [original componentsSeparatedByString:#"-"];
NSString * first = [NSString stringWithFormat:#"(%#)",[components objectAtIndex:0] ];
NSString * second = [NSString stringWithFormat:#"%#-%#",[components objectAtIndex:1],[components objectAtIndex:2]];
NSString * finalString = [NSString stringWithFormat:#"%#%#",first,second];
NSLog(#"Final Result = %#",finalString);
NSString *str = #"123-123-1234";
NSArray *arrForDate = [str componentsSeparatedByString: #"-"];
NSString *str1 = [NSString stringWithFormat:#"(%#) %#-%#",[arrForDate objectAtIndex:0],[arrForDate
objectAtIndex:1],[arrForDate objectAtIndex:2]];
NSLog(#"str1 %#",str1);
TESTED CODE: 100% WORKS
NSString *inputString=#"123-123-1234";
NSArray *TotalString=[inputString componentsSeparatedByString:#"-"];
NSString *outputString = [NSString stringWithFormat:#"(%#) %#-%#",[TotalString objectAtIndex:0],[TotalString objectAtIndex:1],[TotalString objectAtIndex:2]];
NSLog(#"outputString is : %# \n\n",outputString);
OUTPUT:
outputString is : (123) 123-1234
For Dynamic Sollution:
NOTE: if u have more dashes with ur string then it is really hard code everything with objectAtIndex with number 0,1,2,....
moreover it will crash if it has unexpected length
so here is the solution for this
NSString *inputString=#"123-123-1234";
NSArray *TotalString=[inputString componentsSeparatedByString:#"-"];
NSMutableString *outputString=[NSMutableString string];
for (NSMutableString *obj in TotalString) {
if ([TotalString objectAtIndex:0] == obj && [outputString length]<=0) {
outputString=[[outputString stringByAppendingFormat:#"(%#)",obj] mutableCopy];
}
else if ([TotalString objectAtIndex:1] == obj) {
outputString=[[outputString stringByAppendingFormat:#"%#%#",#" ",obj] mutableCopy];
}
else {
outputString=[[outputString stringByAppendingFormat:#"-%#",obj] mutableCopy];
}
}
OUTPUT:
outputString is : (123) 123-1234
NSString *list = #"123-123-1234";
NSArray *listItems = [list componentsSeparatedByString:#"-"];
NSString *result = [NSString stringWithFormat:#"(%#) %#-%#", [listItem objectAtIndex:0], [listItem objectAtIndex:1], [listItem objectAtIndex:2]];