how to use nsdictionary to split strings and swap values - objective-c

I'm new to ios, trying to do something like this
self.dataArray = [dictionary valueForKey:#"LIST"];
{
"List": [
{
"FULLNAME": "FirstName, LastName",
"ID": "281"
}
]
}
I want to swap the value which is in 'FULLNAME', that is I want it to be LastName, FirstName
I tried various methods but it would not work. Can someone tell me how to accomplish this?
Thank you

Assuming you know how to do the dictionary manipulation, here's one way to swap the elements in the string:
NSString* name = #"Firstname, Lastname";
// Remove the space after comma (not necessary if you know the name will always
// have a space after comma, then just split on ', '.
NSString* normalizedName = [name stringByReplacingOccurrencesOfString:#", " withString:#","];
// Split the string on ','.
NSArray* nameParts = [normalizedName componentsSeparatedByString:#","];
// Reverse the array
NSArray* reverseNameParts = [[nameParts reverseObjectEnumerator] allObjects];
// Join the array with ', '
NSString* revname = [reverseNameParts componentsJoinedByString:#", "];
NSLog(#"Reversed name parts: %#", revname);

I believe it should be objectForKey instead of valueForKey, if your dictionary contains arrays.
self.dataArray = [dictionary objectForKey:#"LIST"];
for(NSString *fullname in self.dataArray){
if([fullname isEqualToString:#"FULLNAME"]){
NSArray *name = [fullname componentsSeparatedByString:#","];
NSMutableString* reverseName = [NSMutableString string];
for (int i=[name count]-1; i>=0;i--){
[reverseName appendFormat:#", ", [name objectAtIndex:i]];
//reverse name should be what you are looking for..or something close
}
}
}
hope this helps

Related

Updating key in NSMutableDictionary

json is a NSMutableDictionary with a key "message". I need to "clean" the data in that key using stringByReplacingOccurrencesOfString
NSLog(#"json: %#", json); outputs this:
json: {
conversationId = 61;
countmessagesinconversation = 2;
message = "Messages exist!";
messagesinconversation = (
{
message = "Hi";
messagecreated = "June 24, 2013 16:16";
messageid = 68;
sentby = Thomas;
sentbyID = 1;
title = "Subject";
},
{
message = "What's up?";
messagecreated = "September 22, 2013 17:00";
messageid = 331;
sentby = Steve;
sentbyID = 2;
title = "Subject";
}
);
success = 1;
}
So, this is what I've come up with, but I'm clearly getting it all wrong.
NSString *newstr = [[NSString alloc]init];
for (newstr in [[[json objectForKey:#"messagesinconversation"]allKeys]copy]){
newstr = [newstr stringByReplacingOccurrencesOfString:#" "
withString:#""];
[json setValue:newstr forKey:#"message"];
}
Could somebody please help me out with this and explain so I understand the concept? I know how to do this with an array but what my problem is (I think) is that I do not fully understand how to access the right key in the dictionary.
Edit: Sorry for not being clear in my question. What happens is that if there are two space characters in the key message then " " shows up when I display it on the screen.
//First get the array of message dictionaries:
NSArray * messages = [json objectForKey:#"messagesinconversation"];
//create new array for new messages
NSMutableArray * newMessages = [NSMutableArray arrayWithCapacity:messages.count];
//then iterate over all messages (they seem to be dictionaries)
for (NSDictionary * dict in messages)
{
//create new mutable dictionary
NSMutableDictionary * replacementDict = [NSMutableDictionary dictionaryWithDictionary:dict];
//get the original text
NSString * msg = [dict objectForKey:#"message"];
//replace it as you see fit
[replacementDict setObject:[msg stringByReplacingOccurrencesOfString:#" " withString:#""] forKey:#"message"];
//store the new dict in new array
[newMessages addObject:replacementDict];
}
//you are done - replace the messages in the original json dict
[json setObject:newMessages forKey:#"messagesinconversation"];
Add your array of dictionary in another mutable array
NSMutableArray *msgArray = [[json objectForKey:#"messagesinconversation"] mutableCopy];
Use for loop for access it.
for (int i = 0 ; i < msgArray.count ; i++)
{
[[[msgArray objectAtindex:i] objectForKey:#"message"] stringByReplacingOccurrencesOfString:#" " withString:#""];
}
[self.mainJSONDic setValue:msgArray forKey:#"messagesinconversation"];
Try this code might helpful in your case:
Now that the requirements are more clear I'll try an answer. I try to use the same names as in your question and suggested in erlier answers.
Make json an NSMUtableDictionary where you declare it. Then go forward:
json = [json mutableCopy]; // creates a mutable dictionary based on json which is immutable as result of the json serialization although declared as mutable.
NSMutableArray *msgArray = [[json objectForKey:#"messagesinconversation"] mutableCopy]; //this fetches the array from the dictinary and creates a mutable copy of it.
[json setValue:newstr forKey:#"messagesinconversation"]; // replace the original immutable with the mutable copy.
for (int i = 0; i < [msgArray count]; i++) {
NSMutableDictionary mutableInnerDict = [[msgArray objectAtIndex:i] mutableCopy]; // fetching the i-th element and replace it by a mutable copy of the dictionary within.
[msgArray replaceObjectAtIndex:i withObject:mutableInnerDict]; // it is now mutable and replaced within the array.
NSString *newString = [[[msgArray objectAtindex:i] objectForKey:#"message"] stringByReplacingOccurrencesOfString:#" " withString:#" "]; // crates a new string with all &nbsp removed with blanks.
[mutableInnerDict setValue:newString forKey:#"message"];
}
Regarding the replacement of &nbsp with " ", is this really what you want? I am asking because &nbsp does not occur in your sample data. Or do you want to remove blanks at all?

Appending strings within a loop objective-c

I have a for-in loop running unknown num of times, when its finished running I want to have all names appending like so: name1, name2,name3 and so on.
How do I append the strings within the loop ?
I was thinking of something like this :
if (donePressed)
{
NSString *allFriends;
selectedFriends = friendPicker.selection;
for (NSDictionary * friend in selectedFriends)
{
NSString * friendName = [friend objectForKey:#"name"];
// some built-in method that appends friendName to allFriends with a ", " between them
}
NSLog(#"%#",selectedFriends);
}
NSString *allFriends = [[friendPicker.selection valueForKey:#"name"] componentsJoinedByString:#", "];
I would do this:
NSMutableString *nameString = [[NSMutableString alloc]init];
for loop (...) {
NSString *currentName = [friend objectForKey:#"name"];
[nameString appendString:[NSString stringWithFormat:#"%#, ",currentName]];
}
NSLog(#"%#",nameString);
The answer above mine looks better, that function probably doesn't leave a trailing , at the end of the list. Mine would have to use NSMakeRange() to trim the trailing comma.

split NSString using componentsSeparatedByString

I have a string I need to split. It would be easy using componentsSeparatedByString but my problem is that the separator is a comma but I could have commas that aren't separator.
I explain:
My string:
NSString *str = #"black,red, blue,yellow";
the comma between red and blue must not be considered as separator.
I can determine if comma is a separator or not checking if after it there is a white space.
The goal is to obtain an array with:
(
black,
"red, blue",
yellow
)
This is tricky. First replace all occurences of ', ' (comma+space) with say '|' then use components separated method. Once you are done, again replace '|' with ', ' (comma+space).
Just to complete the picture, a solution that uses a regular expression to directly identify commas not followed by white space, as you explain in your question.
As others have suggested, use this pattern to substitute with a temporary separator string and split by that.
NSString *pattern = #",(?!\\s)"; // Match a comma not followed by white space.
NSString *tempSeparator = #"SomeTempSeparatorString"; // You can also just use "|", as long as you are sure it is not in your input.
// Now replace the single commas but not the ones you want to keep
NSString *cleanedStr = [str stringByReplacingOccurrencesOfString: pattern
withString: tempSeparator
options: NSRegularExpressionSearch
range: NSMakeRange(0, str.length)];
// Now all that is needed is to split the string
NSArray *result = [cleanedStr componentsSeparatedByString: tempSeparator];
If you are not familiar with the regex pattern used, the (?!\\s) is a negative lookahead, which you can find explained quite well, for instance here.
Here is coding implementation for cronyneaus4u's solution:
NSString *str = #"black,red, blue,yellow";
str = [str stringByReplacingOccurrencesOfString:#", " withString:#"|"];
NSArray *wordArray = [str componentsSeparatedByString:#","];
NSMutableArray *finalArray = [NSMutableArray array];
for (NSString *str in wordArray)
{
str = [str stringByReplacingOccurrencesOfString:#"|" withString:#", "];
[finalArray addObject:str];
}
NSLog(#"finalArray = %#", finalArray);
NSString *str = #"black,red, blue,yellow";
NSArray *array = [str componentsSeparatedByString:#","];
NSMutableArray *finalArray = [[NSMutableArray alloc] init];
for (int i=0; i < [array count]; i++) {
NSString *str1 = [array objectAtIndex:i];
if ([[str1 substringToIndex:1] isEqualToString:#" "]) {
NSString *str2 = [finalArray objectAtIndex:(i-1)];
str2 = [NSString stringWithFormat:#"%#,%#",str2,str1];
[finalArray replaceObjectAtIndex:(i-1) withObject:str2];
}
else {
[finalArray addObject:str1];
}
}
NSLog(#"final array count : %d description : %#",[finalArray count],[finalArray description]);
Output:
final array count : 3 description : (
black,
"red, blue",
yellow
)

how to remove spaces, brackets and " from nsarray

I have an array where i am trying to remove the access spaces, brackets and " from the nsarray in order to use componentsSeparatedByString:#";"
NSArray *paths = [dic valueForKey:#"PATH"];
for(NSString *s in paths)
{
NSLog(#"String: %#", s);
}
String: (
"29858,39812;29856,39812;29800,39819;29668,39843;29650,39847;29613,39855;29613,39855;29613,39856;29605,39857;29603,39867;29603,39867;29599,39892;29596,39909;29587,39957;29571,40018;29563,40038;29560,40043"
)
this is the output give as show there are spaces, brackets and " how could i remove them
?
As this line is juz a string inside that array "29858,39812;29856,39812;29800,39819;29668,39843;29650,39847;29613,39855;29613,‌​39855;29613,39856;29605,39857;29603,39867;29603,39867;29599,39892;29596,39909;295‌​87,39957;29571,40018;29563,40038;29560,40043" this line is a string inside the path array and i try using componentsSeparatedByString:#";" it could not be spilt all there are spaces brackets and " inside.
Try stringByTrimmingCharactersInSet:
NSCharacterSet *charsToTrim = [NSCharacterSet characterSetWithCharactersInString:#"() \n\""];
s = [s stringByTrimmingCharactersInSet:charsToTrim];
try to use:
s = [s stringByReplacingOccurrencesOfString:#";"
withString:#""];
it separates the numbers for you and you can work with them as i.e. NSInteger values.
NSString *_inputString = #"29858,39812;29856,39812;29800,39819;29668,39843;29650,39847;29613,39855;29613,39855;29613,39856;29605,39857;29603,39867;29603,39867;29599,39892;29596,39909;29587,39957;29571,40018;29563,40038;29560,40043";
NSString *_setCommonSeparator = [_inputString stringByReplacingOccurrencesOfString:#";" withString:#","];
NSArray *_separetedNumbers = [_setCommonSeparator componentsSeparatedByString:#","];
for (NSString *_currentNumber in _separetedNumbers) {
NSInteger _integer = [_currentNumber integerValue];
NSLog(#"number : %d", _integer);
}

How can I generate a comma-separated string in Objective-C?

I am trying to create comma separated string. e.g. abc,pqr,xyz
I am parsing the xml and want to generate the comma separated string of the values of nodes in xml.
I am doing the following:
if([elementName isEqualToString:#"Column"])
NSString *strTableColumn = [attributeDict objectForKey:#"value"];
I am getting different nodes value in strTableColumn while parsing and want to generate comma separated of this. Please help.
I would do to it like this. Before you start your XML processing, create a mutable array to hold each "Column" value (probably want this to be an iVar in your parser class):
NSMutableArray *columns = [[NSMutableArray alloc] init];
Then parse the XML, adding each string to the array:
if([elementName isEqualToString:#"Column"]) {
[columns addObject:[attributeDict objectForKey:#"value"]];
}
When you're done, create the comma-separated string and release the array:
NSString *strTableColumn = [columns componentsJoinedByString:#","];
[columns release];
columns = nil;
You can use the following code:
NSString *timeCreated = elementName;
NSArray *timeArray = [timeCreated componentsSeparatedByString:#","];
NSString *t = [timeArray objectAtIndex:0];
NSString *t1 = [timeArray objectAtindex:1];
Then append one by one string.
use NSMutableString
then you can use
[yourMutableString appendString:#","];//there is a comma
[yourMutableString appendString:someOtherString];
in this way your strings are separated by comma
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;
}
First thought can be that you parse the data and append commas using the NSString append methods. But that can have extra checks. So better solution is to
Parse data -> Store into array -> Add comma separators -> Finally store in string
// Parse data -> Store into array
NSMutableArray *arrayOfColumns = [[NSMutableArray alloc] init];
if([elementName isEqualToString:#"Column"]){
[arrayOfColumns addObject:[attributeDict objectForKey:#"value"]];
}
// Add comma separators -> Finally store in string
NSString *strTableColumn = [arrayOfColumns componentsJoinedByString:#","];