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 に答える