I have a NSString like this one:
NSString* allSeats = #"1_Male,2_Female,3_Female,4_Male";
I want to split the NSString based on the keywords _Male & _Female and then make two separate strings like these:
NSString* maleSeats = #"1,4";
NSString* femaleSeats = #"2,3";
based on the contents of allSeats variable declared above.
How it will be possible to split NSString and then make 2 seperate strings?
You have to do it yourself. There is no "all done" solution. There are a few ways to do it.
Note: I didn't try my code, I just wrote it, it may don't even compile. But the important thing is that you get the whole idea behind it.
One way could be this one:
NSString *maleSufffix = #"_Male";
NSString *femaleSufffix = #"_Female";
NSMutableArray *femaleSeatsArray = [[NSMutableArray alloc] init];
NSMutableArray *maleSeatsArray = [[NSMutableArray alloc] init];
NSArray *array = [allSeats componentsSeparatedByString:#","];
for (NSString *aSeat in array)
{
if ([aSeat hasSuffix:maleSuffix])
{
[maleSeatsArray addObject:[aSeat stringByReplacingOccurencesOfString:maleSuffix withString:#""]];
}
else if ([aSeat hasSuffix:femaleSuffix])
{
[femalSeatsArray addObject:[aSeat stringByReplacingOccurencesOfString:femaleSuffix withString:#""]];
}
else
{
NSLog(#"Unknown: %#", aSeat);
}
}
NSString *maleSeats = [maleSeatsArray componentsJoinedByString:#","];
NSString *femaleSeats = [femaleSeatsArray componentsJoinedByString:#","];
Of course, you could use different methods on array, enumerating it, use a NSMutableString instead of a NSMutableArray (for femaleSeatsArray or maleSeatsArray, and use adequate methods then in the for loop).
I derived an idea from Larme's Clue and it works as :
Make a method as and call it anywhere :
-(void)seperateSeat
{
maleSufffix = #"_Male";
femaleSufffix = #"_Female";
femaleSeatsArray = [[NSMutableArray alloc] init];
maleSeatsArray = [[NSMutableArray alloc] init];
array = [self.selectedPassengerSeat componentsSeparatedByString:#","];
for (aSeat in array)
{
if ([aSeat hasSuffix:maleSufffix])
{
aSeat = [aSeat substringToIndex:[aSeat length]-5];
NSLog(#"%# is value in final seats ::",aSeat );
[maleSeatsArray addObject:aSeat];
}
else if ([aSeat hasSuffix:femaleSufffix])
{
aSeat = [aSeat substringToIndex:[aSeat length]-7];
NSLog(#"%# is value in final seats ::",aSeat );
[femaleSeatsArray addObject:aSeat];
}
}
totalMales = [maleSeatsArray componentsJoinedByString:#","];
totalFemales = [femaleSeatsArray componentsJoinedByString:#","];
NSLog(#"maleSeatsAre::::%#",totalMales);
NSLog(#"maleSeatsAre::::%#",totalFemales);
}
Related
I have a serious problem about indexing in array. I've been working on this for 2 days and couldn't find answer yet.
I want to do that, search specific character in array then replace it with other string. I'm using replaceObjectAtIndex method but my code is doesn't work.
Here is my code;
NSString *commentText = commentTextView.text;
NSUInteger textLength = [commentText length];
NSString *atSign = #"#";
NSMutableArray *commentArray = [[NSMutableArray alloc] init];
[commentArray addObject:commentText];
for (int arrayCounter=1; arrayCounter<=textLength; arrayCounter++)
{
NSRange isRange = [commentText rangeOfString:atSign options:NSCaseInsensitiveSearch];
if(isRange.location != NSNotFound)
{
commentText = [commentText stringByReplacingOccurrencesOfString:commentText withString:atSign];
[_mentionsearch filtrele:_mentionText];
id<textSearchProtocol> delegate;
[delegate closeList:[[self.searchResult valueForKey:#"user_name"] objectAtIndex:indexPath.row]];
}
}
Ok, now i can find "#" sign in the text and i can match it. But this is the source of problem that, i can not replace any string with "#" sign. Here is the last part of code;
-(void)closeList
{
NSArray *arrayWithSign = [commentTextView.text componentsSeparatedByString:#" "];
NSMutableArray *arrayCopy = [arrayWithSign mutableCopy];
[arrayCopy replaceObjectAtIndex:isRange.location withObject:[NSString stringWithFormat:#"#%#",username]];
}
When im logging isRange.location value, it returns correct. But when im try to run, my application is crashing. So, i can not replacing [NSString stringWithFormat:#"#%#",username] parameter. How can i solve this problem?
If I understand correctly you want to change a substring in a string with a new string. In this case, why don't you use directly the stringByReplacingOccurrencesOfString method of NSString:
NSString *stringToBeChanged = #"...";
NSString *stringToBeChangedWith = #"...";
NSString *commentTextNew = [commentText stringByReplacingOccurrencesOfString:stringToBeChanged withString:stringToBeChangedWith];
I want to show all objects in mutable array on to textfield, label, something else except NSLog
- (IBAction)purchasePressed:(id)sender {
NSMutableArray *addItem = [[NSMutableArray alloc] init];
[addItem addObject:#"Almond"];
[addItem addObject:#"Choc"];
"number" is my label (I'm not sure that all of Objects in MutableArray can be showed on textfield or not?) i can do it only with NSLog.
for (i = 0;i < [addItem count] ; i++ )
{
NSLog(#"%#", addItem);
NSString *test1=(#"%#", addItem);
number.text=test1;
}
Every time you set the text of a label you replace the previous text.
Try replacing your whole loop with something like:
number.text = [addItem componentsJoinedByString:#", "];
Which will create a single string from all of the strings in the array and add that to the label. You could do something similar in your loop if you want to.
If you want a string with all the values concatenated:
NSString *mainString = [NSString alloc] init];
for (NSString *item in addItem) {
mainString = [mainString stringByAppendingString:item];
}
number.text = mainString;
EDIT: Using NSMutableString
NSMutableString *mainString = [[NSMutableString alloc] init];
for (NSString *item in addItem) {
[mainString appendString:item];
}
number.text = mainString;
I was wondering if anyone could lend some assistance. Basically I am calling a web service and then trying to get the large hosted image url. The output from the web service is so:
images = (
{
hostedLargeUrl = "http://i.yummly.com/Crispy-roasted-chickpeas-_garbanzo-beans_-308444.l.jpg";
hostedSmallUrl = "http://i.yummly.com/Crispy-roasted-chickpeas-_garbanzo-beans_-308444.s.jpg";
}
);
The main problem is that the two strings are in only one of my array elements when I think they should be in 2. Also I'm not 100% but possibly they may be a dictionary :-S I'm just not sure. My code is as follows:
NSArray *imageArray = [[NSArray alloc]init];
imageArray = [self.detailedSearchYummlyRecipeResults objectForKey:#"images"];
NSLog(#"imageArray: %#", imageArray);
NSLog(#"count imageArray: %lu", (unsigned long)[imageArray count]);
NSString *hostedLargeurlString = [imageArray objectAtIndex:0];
NSLog(#"imageArrayString: %#", hostedLargeurlString);
The output (nslog's) from the above code is:
2013-04-28 18:59:52.265 CustomTableView[2635:11303] imageArray: (
{
hostedLargeUrl = "http://i.yummly.com/Crispy-roasted-chickpeas-_garbanzo-beans_-308444.l.jpg";
hostedSmallUrl = "http://i.yummly.com/Crispy-roasted-chickpeas-_garbanzo-beans_-308444.s.jpg";
}
)
2013-04-28 18:59:52.266 CustomTableView[2635:11303] count imageArray: 1
2013-04-28 18:59:52.266 CustomTableView[2635:11303] imageArrayString: {
hostedLargeUrl = "http://i.yummly.com/Crispy-roasted-chickpeas-_garbanzo-beans_-308444.l.jpg";
hostedSmallUrl = "http://i.yummly.com/Crispy-roasted-chickpeas-_garbanzo-beans_-308444.s.jpg";
}
Does anyone have any idea how I can seperate the one element into hostedlargeUrl and hostedsmallUrl respectively?
Any help you can provide is greatly appreciated!
Actually the images array contains a dictionary
images = (
{
hostedLargeUrl = "http://i.yummly.com/Crispy-roasted-chickpeas-_garbanzo-beans_-308444.l.jpg";
hostedSmallUrl = "http://i.yummly.com/Crispy-roasted-chickpeas-_garbanzo-beans_-308444.s.jpg";
}
);
so :
NSDictionary *d = [self.detailedSearchYummlyRecipeResults objectForKey:#"images"][0];
NSString *largeURL = d[#"hostedLargeUrl"];
NSString *smallURL = d[#"hostedSmallUrl"];
The value of [imageArray objectAtIndex:0] is a NSDictionary. You've incorrectly specified it as a NSString. You need the following:
NSDictionary *hostedLarguerDictionary =
(NSDictionary *) [imageArray objectAtIndex:0];
and then to access the 'large url' use:
hostedLarguerDictionary[#"hostedLargeUrl"]
or, equivalently
[hostedLarguerDictionary objectForKey: #"hostedLargeUrl"];
looks like an array with in an array so
NSArray* links = [self.detailedSearchYummlyRecipeResults objectForKey:#"images"];
NSString* bigLink = [links objectAtIndex:0];
NSString* smallLink = [links objectAtIndex:1];
or it could be a dictionary
NSDictionary* links = [self.detailedSearchYummlyRecipeResults objectForKey:#"images"];
NSString* bigLink = [links objectForKey:#"hostedLargeUrl "];
NSString* smallLink = [links objectForKey:#"hostedSmallUrl "];
you can see the class of the object by printing out the class name
NSLog(#"Class Type: %#", [[self.detailedSearchYummlyRecipeResults objectForKey:#"images"] class]);
I want to scan NSString (case insensitive) to check whether all elements of an array contain in that String or not ?
Eg.
NSString *string1 = #"Java is pass by value : lets see how?";
NSString *string2 = #"Java is OOP Language";
NSArray *array = [[NSArray alloc] initWithObjects:#"Java",#"Pass",#"value", nil];
In this case string1 pass the test as it contain all keyword from array (i.e. Java,Pass,Value).
So, how can i achieve this functionality ?
I don't test it for speed, and it will fail on case-sensitive strings, but here's another solution (just in case)
NSArray *components = [string1 componentsSeparatedByString:#" "];
NSSet *textSet = [NSSet setWithArray:components];
NSSet *keywordsSet = [NSSet setWithArray:array];
BOOL result = [keywordsSet isSubsetOfSet:textSet];
Keep in mind that componentsSeparatedByString will tokenize very silly, like "how?" instead of "how" you need.
BOOL containsAll = YES;
for (NSString *test in array) {
if ([string1 rangeOfString:test].location == NSNotFound) {
containsAll = NO;
break;
}
}
I am using NSXML to parse out an XML document and add the results to an array of objects. The array has the correct number of objects, but they are full of data from the last object.(i.e. the object at index 0 has the same data as at index 3). I am getting good data back from my server.
//set up my objects and arrays higher in my structure
SignatureResult *currentSignatureResult = [[SignatureResult alloc]init];
Document *currentDoc = [[Document alloc]init];
Role *currentRole = [[Role alloc]init];
NSMutableArray *roleArray = [[NSMutableArray alloc] init];
NSMutableArray *doclistArray2 = [[NSMutableArray alloc] init];
.....there is more parsing up here
//role is defined as an NSXML Element
for (role in [roleList childrenNamed:#"role"]){
NSString *firstName =[role valueWithPath:#"firstName"];
NSString *lastName = [role valueWithPath:#"lastName"];
currentRole.name = [NSString stringWithFormat:#"%# %#",firstName, lastName];
for (documentList2 in [role childrenNamed:#"documentList"])
{
SMXMLElement *document = [documentList2 childNamed:#"document"];
currentDoc.name = [document attributeNamed:#"name"];
[doclistArray2 addObject:currentDoc];
}
currentRole.documentList = doclistArray2;
[roleArray addObject:currentRole];
///I've logged currentRole.name here and it shows the right information
}//end of second for statemnt
currentSignatureResult.roleList = roleArray;
}
///when I log my array here, it has the correct number of objects, but each is full of
///data from the last object I parsed
The cause is that the addObjects: retains for your currentRole object and not creates a copy from that. You can create your new currentRole object inside of the for or you can create a copy from that and add it to the array.
I recommend the following:
for (role in [roleList childrenNamed:#"role"]){
Role *currentRole = [[Role alloc] init];
NSString *firstName =[role valueWithPath:#"firstName"];
NSString *lastName = [role valueWithPath:#"lastName"];
currentRole.name = [NSString stringWithFormat:#"%# %#",firstName, lastName];
for (documentList2 in [role childrenNamed:#"documentList"])
{
SMXMLElement *document = [documentList2 childNamed:#"document"];
currentDoc.name = [document attributeNamed:#"name"];
[doclistArray2 addObject:currentDoc];
}
currentRole.documentList = doclistArray2;
[roleArray addObject:currentRole];
///I've logged currentRole.name here and it shows the right information
[currentRole release];
}//end of second for statemnt