我怎样才能知道2串之间的串? 例如:
<id> 100 </id>
我想从这个字符串得到100。
我也试试这个代码,但它doesn't工作。 该NSLog
是:
<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)]);
你在哪里几乎都有,但范围位置是不是结束的开始。 所以,你必须添加的范围的长度。
既然你感动,你字符串的开始,你需要用很短的偏移长度:
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)]);
在斯威夫特 :
extension String {
func slice(from: String, to: String) -> String? {
return (range(of: from)?.upperBound).flatMap { substringFrom in
(range(of: to, range: substringFrom..<endIndex)?.lowerBound).map { substringTo in
String(self[substringFrom..<substringTo])
}
}
}
}
输入
let serverOutput = "<id>100</id>"
let resultString = serverOutput.slice(from: "<id>", to: "</id>")
print(resultString)
产量
100
这是怎么NSRange
定义:
typedef struct _NSRange {
NSUInteger location;
NSUInteger length;
} NSRange;
所以,如果你想获得100
,你应该串这样的:
NSRange substringRange = NSMakeRange(start.location + start.length, end.location - start.length);
NSLog(@"%@", [serverOutput substringWithRange:substringRange]);
NSString *serverOutput = @"<id>100</id>";
serverOutput = [serverOutput stringByReplacingOccurrencesOfString:@"<id>" withString:@""];
serverOutput = [serverOutput stringByReplacingOccurrencesOfString:@"</id>" withString:@""];
NSLog(@"%@",serverOutput);
我认为你应该使用正则表达式。
NSString *serverOutput = @"<id>100</id>";
NSString *pattern = @"<id>([0-9]+)</id>";
NSError *error;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
options:NSRegularExpressionCaseInsensitive
error:&error];
NSTextCheckingResult *match = [regex firstMatchInString:serverOutput
options:NSMatchingReportProgress
range:NSMakeRange(0, serverOutput.length)];
if (!error && match && match.numberOfRanges >= 2) {
NSRange range = [match rangeAtIndex:1];
NSLog(@"%@", [serverOutput substringWithRange:range]);
}
你想在第一字符串的结尾开始,所以你只需要改变:
NSLog(@"%@",[serverOutput substringWithRange:NSMakeRange(start.location, end.location)]);
至:
NSLog(@"%@",[serverOutput substringWithRange:NSMakeRange(NSMaxRange(start), end.location - start.length)]);
请注意,我也减去开始字符串的长度,因为我们只是通过抵消了。