Question

I have a big NSString object as shown below. I want to parse this string to fetch all icmp_seq and time values in it. The code I have written always gives me last value.

Any idea how to do this in better way except for splitting it by new line character and then run the parser on each split.

64 bytes from 74.125.129.105: icmp_seq=0 ttl=43 time=23.274 ms
64 bytes from 74.125.129.105: icmp_seq=1 ttl=43 time=28.704 ms
64 bytes from 74.125.129.105: icmp_seq=2 ttl=43 time=23.519 ms
64 bytes from 74.125.129.105: icmp_seq=3 ttl=43 time=23.548 ms
64 bytes from 74.125.129.105: icmp_seq=4 ttl=43 time=23.517 ms
64 bytes from 74.125.129.105: icmp_seq=5 ttl=43 time=23.293 ms
64 bytes from 74.125.129.105: icmp_seq=6 ttl=43 time=23.464 ms
64 bytes from 74.125.129.105: icmp_seq=7 ttl=43 time=23.323 ms
64 bytes from 74.125.129.105: icmp_seq=8 ttl=43 time=23.451 ms
64 bytes from 74.125.129.105: icmp_seq=9 ttl=43 time=23.560 ms

Code:

-(void)parsePingData:(NSString *)iData {
  NSRange anIcmpRange = [iData rangeOfString:@"icmp_seq"];
  NSRange aTtlRange =[iData rangeOfString:@"ttl"];
  NSRange icmpDataRange = NSMakeRange(anIcmpRange.location + 1, aTtlRange.location - (anIcmpRange.location + 1));
  NSLog(@"Output=%@",[iData substringWithRange:icmpDataRange]);    
}
Was it helpful?

Solution

Based on the code you posted with some changes, we can get to something like this:

NSRange range = NSMakeRange(0, largeString.length);
while (range.location != NSNotFound) {
  NSRange icmpRange = [largeString rangeOfString:@"icmp_seq=" options:NSLiteralSearch range:range];
  range.location = icmpRange.location + icmpRange.length;
  range.length = largeString.length - range.location;
  if (range.location != NSNotFound) {
    NSRange ttlRange = [largeString rangeOfString:@" ttl" options:NSLiteralSearch range:range];
    if (ttlRange.location != NSNotFound) {
      NSLog(@"icmp_seq = [%@]", [largeString substringWithRange:NSMakeRange(range.location, ttlRange.location - range.location)]);
    }
  }
}

Keeping an updated range and using rangeOfString:options:range, we can search only on the part of the string that we didn't search yet.

OTHER TIPS

Here is a way to do it. I am sure there is a better solution so sorry if this seems really bad. But you could do:

NSArray *stringArray = [largeString componentsSeparatedByString: @":"];

Then do a for loop:

for (int i = 1; i < stringArray.count; i++) {
     [self parsePingData:[stringArray objectAtIndex:i]];
}

I started this on int i = 1 because index 0 would not contain any values you want.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top