iCodes
iCodes

Reputation: 1457

Getting subString from string ios?

I have a following string in iOS :-

[{"status":"0","eventid":"126"}]15.511563,73.809732[{"status":"0"}]

And I am trying to fetch this :-

[{"status":"0","eventid":"126"}]

i.e. the entire portion of string before first ] closing bracket.

I tried this in which I get a substring of 31 characters, but this won't work if the contents between the brackets changes.

NSRange start = [result1 rangeOfString:@"["];

NSString *shortString =[result1 substringWithRange:NSMakeRange(start.location, 31)];

result1 = [result1 substringToIndex:shortString.length];
NSLog(@"Response- %@",result1);

What is the correct approach?

Upvotes: 0

Views: 199

Answers (3)

Himanshu Joshi
Himanshu Joshi

Reputation: 3399

Make the END Range also

NSRange start;
NSRange end;
start = [result1 rangeOfString: @"["];
end = [result1 rangeOfString: @"]"];

NSString *newResult = [result1 substringWithRange:NSMakeRange(start.location+1, end.location)];

NSLog(@"%@", newResult);

Upvotes: 1

Flovdis
Flovdis

Reputation: 3095

You could try using a NSRegularExpression:

NSError *error = NULL;
NSRegularExpression *regex =
    [NSRegularExpression regularExpressionWithPattern:@"\\[(.*?)\\]"
         options:NSRegularExpressionCaseInsensitive
           error:&error];

Now, search for the first match:

NSString *string = @"[{\"status\":\"0\",\"eventid\":\"126\"}]15.511563,73.809732[{\"status\":\"0\"}]";
NSTextCheckingResult *match =
    [regex firstMatchInString:string
                      options:0
                        range:NSMakeRange(0, [string length])];

Now you can get the range for the capture group:

NSRange block = [match rangeAtIndex:1];

Upvotes: 0

Wain
Wain

Reputation: 119031

Just like you are getting the start range (NSRange start = [result1 rangeOfString:@"["];), also get the end range:

NSRange end = [result1 rangeOfString:@"]"];

Now you have enough information to extract the substring:

NSString *result = [result1 substringWithRange:NSMakeRange(start.location, end.location - start.location)];

In your current code, you don't need to use substring... methods twice as you have already extracted the string you want in the first call. Making the second call is just ignoring the bit of code which found the start location and assuming that you always want the substring from the start of the string, which is less flexible.

Upvotes: 1

Related Questions