gpt4 book ai didi

objective-c - 解析一个大的 NSString

转载 作者:行者123 更新时间:2023-12-03 17:13:20 27 4
gpt4 key购买 nike

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

知道如何以更好的方式做到这一点,除了用换行符分割它,然后在每个分割上运行解析器。

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

最佳答案

根据您发布的经过一些更改的代码,我们可以得到如下结果:

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,我们只能搜索字符串中尚未搜索的部分。

关于objective-c - 解析一个大的 NSString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14615467/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com