How to separate parts of NSString? - iphone

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

Related

Comparing with NSMutableArray

In my Array 1, which I loaded images from NSDocumentDirectory, I loaded them and add a NSMutableDictionary:
self.images = [NSMutableArray array];
for(int i = 0; i <= 8; i++)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"Images%d.png", i]];
if([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]){
NSMutableDictionary *container = [[NSMutableDictionary alloc] init];
[container setObject:[UIImage imageWithContentsOfFile:savedImagePath] forKey:#"image"];
[container setObject:[NSNumber numberWithInt:i] forKey:#"index"];
[images addObject:container];
}
}
In my other array Array 2, I loaded them from the app.
self.images = [NSMutableArray arrayWithObjects:
#"01.jpg",#"02.jpg",#"03.jpg",#"04.jpg",#"05.jpg",#"06.jpg",#"07.jpg",nil];
I was able to add string to Array 2 like this:
for (int x=1; x<8;x++) {
// add as NSString
[images addObject:[NSString stringWithFormat:#"%d", x]];
}
And was able to compare Array 2 like this:
NSInteger index = carousel.currentItemIndex;
if ([[images objectAtIndex:index] intValue] == 1){
What I wanted to do, is to do it to Array 1.
I know Array 1 has been already added with NSNumber, but Im kinda new to NSMutableDictionary so I can't do it the same as Array 2.
Can it be done the same as my Array 2 or what is the other way?
Thanks for the help.
Actually Here you have the array of dictionaries, because you are adding the dictionary which has two objects with keys image and index
So, for retrieving the array of dictionaries,
just log it and see what happens
Edit 2.0
for(int i=0; i< [images count]; i++){
NSNumber *num =[[images objectAtIndex:i] objectForKey:#"index"];
int index = [num intValue];
NSLog(#"%d",index)
}

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.

how can I convert string to an array with separator?

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

Memory leak in NSMutableArray, NSArray, NSString in iPhone SDK

In my app, I got Memory leaks in NSMutableArray, NSArray and NSString.
Here is the code.
NSString *subQuery = [NSString stringWithFormat:#"SELECT %# FROM tbl_lang WHERE glossary = '%#'",append1,glossaryName];
NSArray *subArray1 = [[[self returnExecuteQuery:subQuery] mutableCopy] autorelease];
[subArray addObjectsFromArray:subArray1];
NSString *columnQuery = [NSString stringWithFormat:#"select AutoID,%# from tbl_lang where glossary='%#'",lblshortName.text,glossaryName];
NSArray *newArray =[[[self returnExecuteQuery:columnQuery] mutableCopy] autorelease];
[langArray addObjectsFromArray:newArray];
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
for (int i=0; i<[newArray count]; i++) {
NSString *cellText = [[newArray objectAtIndex:i] valueForKey:[NSString stringWithFormat:#"%#",lblshortName.text]];
if (cellText != (NSString *)[NSNull null] && ![cellText isEqualToString:#""] ) {
NSString *decodedString3 = [NSString stringWithUTF8String:[cellText cStringUsingEncoding:[NSString defaultCStringEncoding]]];
[tempArray addObject:[NSString stringWithFormat:#"%# : %#",lblshortName.text, decodedString3]];
}
else {
[tempArray addObject:#"<empty>"];
}
NSString *detail = #"_________________";
for (int j=0; j<[lableNameArray count]; j++) {
NSString *checkNull=[[subArray1 objectAtIndex:i] valueForKey:[NSString stringWithFormat:#"%#",[lableNameArray objectAtIndex:j]]];
if(checkNull != (NSString *)[NSNull null] && checkNull.length > 0)
{
NSString *decodedString4 = [NSString stringWithUTF8String:[checkNull cStringUsingEncoding:[NSString defaultCStringEncoding]]];
detail = [NSString stringWithFormat:#"%#\n%# : %# ",detail,[lableNameArray objectAtIndex:j],decodedString4];
}
}
[detailTextArray addObject:detail];
}
When I run in Instruments I got leaks in
-subArray1 in second line.
-detail (NSString) in second for loop.
And subArray and langArray are my global arrays.
If I remove mutableCopy from NSArray *newArray =[[[self returnExecuteQuery:columnQuery] mutableCopy] autorelease]; and NSArray *subArray1 = [[[self returnExecuteQuery:subQuery] mutableCopy] autorelease]; then subArray and langArray doesnot retain values.
How to avoid memory leak in this code?
Olease try this one, in above code you are creating two many objects that belong to autorelease pool here is one version where I tried to handle release of those string variables.
Second this is that the leak of detail is because you are de-referencing it many times in your code. And for subArray1 please see the comment
NSMutableString *subQuery =[ [NSMutableString alloc] initWithFormat:#"SELECT %# FROM tbl_lang WHERE glossary = '%#'",append1,glossaryName];
// please make returnExecuteQuery's returned array autorelease if it is not.
NSArray *subArray1 = [[self returnExecuteQuery:subQuery] mutableCopy] ;
[subArray addObjectsFromArray:subArray1];
[subQuery release];
NSMutableString *columnQuery ==[ [NSMutableString alloc] initWithFormat:#"select AutoID,%# from tbl_lang where glossary='%#'",lblshortName.text,glossaryName];
NSArray *newArray =[[self returnExecuteQuery:columnQuery] mutableCopy] ;
[langArray addObjectsFromArray:newArray];
[columnQuery relese];
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
for (int i=0; i<[newArray count]; i++) {
NSMutableString *tempKey = [[NSMutableString alloc]initWithFormat:#"%#",lblshortName.text]];
NSString *cellText = [[newArray objectAtIndex:i] valueForKey:tempKey];
[tempKey release];
if (cellText != (NSString *)[NSNull null] && ![cellText isEqualToString:#""] ) {
NSString *decodedString3 = [NSString stringWithUTF8String:[cellText cStringUsingEncoding:[NSString defaultCStringEncoding]]];
NSMutableString *tempString = [[NSMutableString alloc] initWithFormat:#"%# : %#",lblshortName.text, decodedString3]];
[tempArray addObject:tempString];
[tempString release];
}
else {
[tempArray addObject:#"<empty>"];
}
NSMutableString *detail = nil;
for (int j=0; j<[lableNameArray count]; j++)
{
detail = [[ NSMutableString alloc]initWithString:#"_________________"];
NSMutableString *key = [[NSMutableString alloc]initWithFormat:#"%#",[lableNameArray objectAtIndex:j]];
NSString *checkNull=[[subArray1 objectAtIndex:i] valueForKey:key];
[key release];
if(checkNull != (NSString *)[NSNull null] && checkNull.length > 0)
{
NSString *decodedString4 = [NSString stringWithUTF8String:[checkNull cStringUsingEncoding:[NSString defaultCStringEncoding]]];
[detail setString:[NSString stringWithFormat:#"%#\n%# : %# ",detail,[lableNameArray objectAtIndex:j],decodedString4]];
}
[detailTextArray addObject:detail];
[detail release];
}
}
[subArray1 release];
[newArray release];
UPDATE : Please do read comments in the code and reply back so that things could be improved.
NSMutableString *subQuery =[ [NSMutableString alloc] initWithFormat:#"SELECT %# FROM tbl_lang WHERE glossary = '%#'",append1,glossaryName];
//*****NOTE THIS POINT ----> please make returnExecuteQuery's returned array autorelease if it is not.
NSArray *subArray1 = [[self returnExecuteQuery:subQuery] mutableCopy] ;
[subArray addObjectsFromArray:subArray1];
[subQuery release];
NSMutableString *columnQuery ==[ [NSMutableString alloc] initWithFormat:#"select AutoID,%# from tbl_lang where glossary='%#'",lblshortName.text,glossaryName];
//*****NOTE THIS POINT ----> please make returnExecuteQuery's returned array autorelease if it is not.
NSArray *newArray =[[self returnExecuteQuery:columnQuery] mutableCopy] ;
[langArray addObjectsFromArray:newArray];
[columnQuery relese];
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
for (int i=0; i<[newArray count]; i++) {
NSMutableString *tempKey = [[NSMutableString alloc]initWithFormat:#"%#",lblshortName.text]];
NSString *cellText = [[newArray objectAtIndex:i] valueForKey:tempKey];
[tempKey release];
if (cellText != (NSString *)[NSNull null] && ![cellText isEqualToString:#""] ) {
NSString *decodedString3 = [NSString stringWithUTF8String:[cellText cStringUsingEncoding:[NSString defaultCStringEncoding]]];
NSMutableString *tempString = [[NSMutableString alloc] initWithFormat:#"%# : %#",lblshortName.text, decodedString3]];
[tempArray addObject:tempString];
[tempString release];
}
else {
[tempArray addObject:#"<empty>"];
}
NSMutableString *detail = [[ NSMutableString alloc]initWithString:#"_________________"];
for (int j=0; j<[lableNameArray count]; j++)
{
NSMutableString *key = [[NSMutableString alloc]initWithFormat:#"%#",[lableNameArray objectAtIndex:j]];
NSString *checkNull=[[subArray1 objectAtIndex:i] valueForKey:key]; //also here if you note you are using subArray1 not subArray?
[key release];
if(checkNull != (NSString *)[NSNull null] && checkNull.length > 0)
{
NSString *decodedString4 = [NSString stringWithUTF8String:[checkNull cStringUsingEncoding:[NSString defaultCStringEncoding]]];
[detail setString:[NSString stringWithFormat:#"%#\n%# : %# ",detail,[lableNameArray objectAtIndex:j],decodedString4]];
break;//I am not sure why you are checking this condition but assume that you want to get NOT NULL VALUE and add it to array?
}
}
[detailTextArray addObject:detail];
[detail release];
}
[subArray1 release];
[newArray release];
UPDATE 2:
if(checkNull != (NSString *)[NSNull null] && checkNull.length > 0)
{
NSString *decodedString4 = [NSString stringWithUTF8String:[checkNull cStringUsingEncoding:[NSString defaultCStringEncoding]]];
[detail appendFormat:#"%#\n%# : %# ",detail,[lableNameArray objectAtIndex:j],decodedString4]];
}
Thanks,
Not sure what is causing the memory leak, but this may help. This is a more direct way of copying the arrays, and may result in avoiding the leak:
NSArray *langArray =[[NSArray alloc] initWithArray: [self returnExecuteQuery:columnQuery] copyItems: YES];
This basically makes a one-level deep copy of the array returned by returnExecuteQuery. You can read about it in more detail in Collections Programming Topics.
I'm not sure how mutableCopy works and that may have something to do with the leak. If it copies the objects in the old array & then adds them to the new array, they may enter the array with a retain count of 2 (1 from the copy, and 1 from being added to an array.) It doesn't make much sense that it should work this way. But, if it does, that could account for the leak.
You could start by releasing your tempArray once done with it (after the loops).
Often, the higher levels leaks are hidden in the flood of lower level ones (ie a container leaking causes all its content to be leaked as well), which might be the case for your string.
Using mutableCopy] autorelease]; is fine by the way.