iOS 获取 2 个字符串之间的字符串 [英] iOS Get String between 2 Strings
本文介绍了iOS 获取 2 个字符串之间的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在两个已知字符串之间获取字符串?例如:
How can I get a string between 2 known strings? For example:
<id> 100 </id>
我想从这个字符串中得到 100.
I want to get the 100 from this string.
我已经尝试过此代码,但它不起作用.NSLog
是:
I have try this code but it doesn´t work. The NSLog
is:
<id>100
代码:
NSString *serverOutput = @"<id>100</id>";
NSRange start = [serverOutput rangeOfString:@"<id>"];
NSRange end = [serverOutput rangeOfString:@"</id>"];
NSLog(@"%@",[serverOutput substringWithRange:NSMakeRange(start.location, end.location)]);
推荐答案
你就在那里,但范围位置是开始而不是结束.所以你必须添加范围的长度.
You where nearly there, but the range location is the start of the not the end. So you have to add the length of the range.
由于您移动了字符串的开头,因此需要使用偏移量缩短长度:
Since the you moved the start of you string, you need to short the length with the offset:
NSString *serverOutput = @"<id>100</id>";
NSRange startRange = [serverOutput rangeOfString:@"<id>"];
NSRange endRange = [serverOutput rangeOfString:@"</id>"];
NSInteger start = NSMaxRange (startRange);
NSInteger length = endRange.location - startRange.length;
NSLog(@"%@", [serverOutput substringWithRange:NSMakeRange(start, length)]);
这篇关于iOS 获取 2 个字符串之间的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文