NSString substring processing - ios

I have a string with the following value:
[{ProjLead=irshad, ProjName=irshad proj, ProjectId=365}]
I would like to get the value for ProjLead, ProjName and ProjectId separately. How can I do it?

You can combine some methods from NSString class.
Something like this:
NSString *string = #"[{ProjLead=irshad, ProjName=irshad proj, ProjectId=365}]";
NSString *parametersString = [string substringWithRange:NSMakeRange(2, string.length - 4)];
NSArray *parameters = [parametersString componentsSeparatedByString: #", "];
NSMutableArray *values = [NSMutableArray array];
for (NSString *parameter in parameters) {
[values addObject:[[parameter componentsSeparatedByString:#"="] objectAtIndex:1]];
}
values array is what you want.

Related

Changing NSString value (displayed as number) to two decimal places and make a percentage

When I retrieve my JSONResponse i retrieve a number that appears as 0.2434309606330154. This is the number I want, however it isn't in the format that I want. It is set up in a way that with three other response it equals to 1.
I've tried converting it to an NSNumber but it didn't work.
NSDictionary *parameters = #{
#"data": text.text,
};
NSMutableString *parameterString = [NSMutableString string];
for (NSString *key in [parameters allKeys]) {
if ([parameterString length]) {
[parameterString appendString:#"&"];
}
[parameterString appendFormat:#"%#=%#", key, parameters[key]];
}
NSLog(#"A: %#", jsonResponse[#"results"][#"A"]);
ALabel.text = [NSString stringWithFormat:#"%#",jsonResponse[#"results"][#"A"]];
NSString *string = [NSString stringWithFormat:#"%#",jsonResponse[#"results"][#"A"]];
CGFloat float = [string floatValue];
ALabel.text = [NSString stringWithFormat:#"%.02f",float];
In Swift 1.2:
self.ALabel?.text = NSString(format: "%.02f%%", string.floatValue) as String
NSString *string = [NSString stringWithFormat:#"%#",jsonResponse[#"results"][#"A"]];
ALabel.text = [NSString stringWithFormat:#"%.02f%%",string.floatValue];
Here output will be - 0.24%

Put multiple arrays in Dictionary

I am parsing a CSV file multiple times with for loop, here I need to store these arrays one by one dictionary. There are very less questions in stack about adding NSArray to NSDictionary. I am parsing CSV with below code but I strucked at storing in NSDictionary, The program is terminating and showing warning at assigning string to dictionary
for (i=0; i<=57; i++) {
NSString *keysString = [csvArray objectAtIndex:i];
NSArray *keysArray = [keysString componentsSeparatedByString:#","];
NSLog(#"Serail No %d %#",i,keysArray);
NSString *string = [NSString stringWithFormat:#"%d", i];
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjects: keysArray forKeys: string];
}
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
for (i=0; i<=57; i++) {
NSString *keysString = [csvArray objectAtIndex:i];
NSArray *keysArray = [keysString componentsSeparatedByString:#","];
NSString *key = [NSString stringWithFormat:#"serial%d",i];
[dict setObject:keysArray forKey:key];
}
To get back data from dictionary,
NSArray *array = [dict valueForKey:#"serial24"];//to get array 24.
If I understand you correctly, you want to add the arrays to a dictionary, with the key being the string value of integer i ? What you need to do is allocate the dictionary outside your loop -
NSMutableDictionary *dict=[NSMutableDictionary new];
for (i=0; i<=57; i++) {
NSString *keysString = [csvArray objectAtIndex:i];
NSArray *keysArray = [keysString componentsSeparatedByString:#","];
NSLog(#"Serial No %d %#",i,keysArray);
NSString *string = [NSString stringWithFormat:#"%d", i];
dict[string]=keysArray;
}
I am not sure why you would want to do this, because this is basically an array. You could simply do -
NSMutableArray *outputArray=[NSMutableArray new];
for (NSString *keysString in csvArray) {
NSArray *keysArray = [keysString componentsSeparatedByString:#","];
[outputArray addObject:keysArray];
}

uilabel text with new line only when required

this is what i am using:
it works if address, city, zip.....length >0.(these field may grow in future)
self.addressInfoLbl.text = [NSString stringWithFormat:#"%#\n%#\n%#\n%#\n%#", address, city, zip, state, country];(numberofline == 0)
but if any of them length =0 then i got unnecessary new line.
i am working on manually preparing(appending \n).if there are more and more fields then doing it manuallt is really hard.
Is there any other proper way.Am i doing it right.
Thanks
Try following code. It creates array of your strings, removes empty strings and then concatenates them with componentsJoinedByString :
NSArray *strings = #[address, city, zip, state, country];
strings = [strings filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"length > 0"]];
NSString *resultString = [strings componentsJoinedByString:#"\n"];
You can join an array of objects into a string with a separator:
NSArray *props = [NSArray arrayWithObjects: address, city, state, nil];
NSString *joinedString = [props componentsJoinedByString:#"\n"];
and you will get:
"6th avenue\nAtlanta\nGeorgia"
If you don't know the amount of properties, use NSMutableArray instead of NSArray and add your properties at runtime.
Try this once,
NSMutableString *joinedString=[NSMutableString string];
NSArray *arr = [NSArray arrayWithObjects: address, city, state, nil];
for(NSString *str in arr)
{
if([str length]>0) [joinedString appendFormat:#"\n%#", str];
}
NSString *resultString=[joinedString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(#"%#", resultString);
Lbl.numberOfLines=0;
Lbl.lineBreakMode=NSLineBreakByCharWrapping;
try this code, it not optimal but it can resolve youy issue
NSArray *arr = [NSArray arrayWithObjects: #"address", #"", #"state", nil];
NSString *addressInfo = #"";
for (NSString *str in arr) {
if (str.length > 0) {
addressInfo = [addressInfo stringByAppendingString:[NSString stringWithFormat:#"\n%#", str]];
}
}
if (addressInfo && ![#"" isEqualToString:addressInfo])
addressInfo = [addressInfo substringFromIndex:1];
NSLog(#"address Info = %#", addressInfo);

NSString remove duplicated substrings

How can I remove duplicated substings from string? For ex. I have: aaa,bbb,ttt,bbb,rrr.
And in result I want to have aaa,bbb,ttt,rrr (deleted duplicated bbb). I hope for your help. Thanks.
You can do it like this:
NSMutableSet *seen = [NSMutableSet set];
NSMutableString *buf = [NSMutableString string];
for (NSString *s in [str componentsSeparatedByString:#","]) {
if (![seen containsObject:s]) {
[seen add:s];
[buf appendFormat:#",%#", s];
}
}
NSString *res = [buf length] ? [buf substringFromIndex:1] : #"";
Do it in three steps
1) NSArray *items = [theString componentsSeparatedByString:#","];
2) remove duplicate element from array
NSArray* array = [NSArray arrayWithObjects:#"test1", #"test2", #"test1", #"test2",#"test4", nil];
NSArray* filteredArray = [[NSArray alloc] init];
NSSet *set= [NSOrderedSet orderedSetWithArray:array];
filteredArray = [set allObjects];
3) Concate String from array
NSString *myString = [myArray componentsJoinedByString:#","];
You can use NSMutableDictionary;
In dictionary there are two elements;
1. Key
2. Value
Just set Keys as your array elements;
Special point is that 'Key' can't be duplicate;
Now just get array of Keys by using [dictionary allKeys];
Now, at this stage you have unique values in new array;

IOS: How to read specific data in one list of XML

When I use NSXMLParser to parse XML in iPhone app, I know how to do it in the scenario like this:
> <title>L3178 : Freiensteinau Richtung Grebenhain</title> // From XML
But, if I want to extract data from a list, e.x. I want to get the lat and lon from <>id>, how should I deal with that?
<>id>
http://www.freiefahrt.info/?id=468B0243-E15C-4580-9AD2 14D8CF692999&lon=9.3495&lat=50.49465&country=DE&filter=0&expires=2013-12-20T03:13:00
<>/id>
It is very strange if I use instead of <>id>, it will disappear. So, I have to use this ugly notation.
Thank you in advance!
Create a method which extracts parameters from urlString
- (NSDictionary *)paramsFromURLString:(NSString *)urlString
{
NSRange range = [urlString rangeOfString:#"?"];
NSString *subString = [urlString substringFromIndex:range.location+range.length];
NSArray *components = [subString componentsSeparatedByString:#"&"];
NSMutableDictionary *params = [NSMutableDictionary dictionary];
for (NSString *string in components) {
NSRange subRange = [string rangeOfString:#"="];
NSString *key = [string substringToIndex:subRange.location];
NSString *value = [string substringFromIndex:subRange.location+subRange.length];
[params setObject:value forKey:key];
}
return params;
}
From the params find the lat and lon
NSString *urlString = #"http://www.freiefahrt.info/?id=468B0243-E15C-4580-9AD2 14D8CF692999&lon=9.3495&lat=50.49465&country=DE&filter=0&expires=2013-12-20T03:13:00";
NSDictionary *params = [self paramsFromURLString:urlString];
NSString *latitude = params[#"lat"];
NSString *longitude = params[#"lon"];

Resources