1

我有一个大的 NSString 对象,如下所示。我想解析这个字符串以获取其中的所有 icmp_seq 和时间值。我写的代码总是给我最后的价值。

任何想法如何以更好的方式做到这一点,除了用换行符分割它,然后在每次分割时运行解析器。

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

代码:

-(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]);    
}
4

2 回答 2

1

根据您发布的代码进行了一些更改,我们可以得到这样的结果:

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)]);
    }
  }
}

保持更新的范围并使用rangeOfString:options:range,我们只能搜索我们尚未搜索的字符串部分。

于 2013-01-31T00:00:30.607 回答
0

这是一种方法。我相信有一个更好的解决方案,如果这看起来真的很糟糕,我很抱歉。但你可以这样做:

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

然后做一个for循环:

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

我开始这样做是int i = 1因为索引 0 不会包含您想要的任何值。

于 2013-01-30T23:09:50.343 回答