Praveenkumar
Praveenkumar

Reputation: 24506

Formatting a String in Objective - C

I'm getting a response from webservice as a string like below one -

brand=company%%samsung@@modelnumber=webmodel%%GT1910@@Sim=Single%%SingleSim@@3g=yes%%Yes@@wifi=yes%%yes(2.1 mbps upto)

I'm confusing that to format my response like below one -

brand=samsung
modelnumber=GT1910
Sim=SingleSim
3g=Yes
wifi=(2.1 mbps upto)

I've tried to remove the special characters (@@ and %%)

specialString = [specialString stringByReplacingOccurrencesOfString:@"@@" withString:@"\n"];
specialString = [specialString stringByReplacingOccurrencesOfString:@"%%" withString:@"\n"];
specialString= [specialString stringByReplacingOccurrencesOfString:@" " withString:@""];

My output was -

brand=company
samsung
modelnumber=webmodel
GT1910
Sim=Single
SingleSim
3g=yes
Yes
wifi=yes
(2.1 mbps upto)

How to remove unwanted words.

Upvotes: 0

Views: 160

Answers (3)

Luke
Luke

Reputation: 14138

You can't use simple find and replace because there are parts of the original string you don't want.

Untested, but this will probably work:

NSArray *parts = [specialstring componentsSeparatedByString:@"@@"];
NSMutableArray *result = [[NSMutableArray alloc] init];
for(NSString *piece in parts) {
    NSArray *pairs = [piece componentsSeparatedByString:@"="];
    if([pairs count] > 1) {
        NSString *key = [pairs objectAtIndex:0];
        NSString *values = [pairs objectAtIndex:1];
        NSArray *avalues = [values componentsSeparatedByString:@"%%"];
        [result addObject:[NSString stringWithFormat:@"%@=%@", key, [avalues lastObject]]];
    }
}

NSLog(@"%@", [result componentsJoinedByString:@"\n"]);
// [result release]; // Uncomment if ARC is turned off

First splits by @@ and iterates over array. Then splits by = to get key on left side (index 0). Takes right side (index 1) and splits by %% and uses last value.

Upvotes: 4

Narayana Rao Routhu
Narayana Rao Routhu

Reputation: 6323

Trim like below it will work

NSString *strRes = @"brand=company%%samsung@@modelnumber=webmodel%%GT1910@@Sim=Single%%SingleSim@@3g=yes%%Yes@@wifi=yes%%yes(2.1 mbps upto)";
strRes = [strRes stringByReplacingOccurrencesOfString:@"=" withString:@"--"];
strRes = [strRes stringByReplacingOccurrencesOfString:@"@@" withString:@"\n"];
NSRange rangeForTrim;
while ((rangeForTrim = [strRes rangeOfString:@"--[^%%]+%%" options:NSRegularExpressionSearch]).location != NSNotFound)
    strRes = [strRes stringByReplacingCharactersInRange:rangeForTrim withString:@"="];

NSLog(@"%@",strRes);

Upvotes: 1

Ravi
Ravi

Reputation: 8309

Well, I can't write the code right away but here's what you gotta do:

  • Replace all %% with (space)
  • Replace all @@ with \n
  • Remove all words between = and (space)

Upvotes: 0

Related Questions