xcode 从 NSString 获取子字符串直到到达特定单词
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9243196/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get a substring from an NSString until arriving to a specific word
提问by Guy Daher
Let us say I have this NSString
: @"Country Address Tel:number"
.
How can I do to get the substring that is before Tel
? (Country Address )
And then How can I do to get the substring that is after Tel
? (number)
让我们说我有这个NSString
:@"Country Address Tel:number"
。如何获取之前的子字符串Tel
?(国家/地区地址)然后我该怎么做才能获得后面的子字符串Tel
?(数字)
回答by zaph
Use NSScanner:
使用 NSScanner:
NSString *string = @"Country Address Tel:number";
NSString *match = @"tel:";
NSString *preTel;
NSString *postTel;
NSScanner *scanner = [NSScanner scannerWithString:string];
[scanner scanUpToString:match intoString:&preTel];
[scanner scanString:match intoString:nil];
postTel = [string substringFromIndex:scanner.scanLocation];
NSLog(@"preTel: %@", preTel);
NSLog(@"postTel: %@", postTel);
NSLog output:
NSLog 输出:
preTel: Country Address
postTel: number
preTel:国家地址
postTel:号码
回答by Amit Shah
Easiest way is if you know the delimiter, (if it is always :
) you can use this:
最简单的方法是如果你知道分隔符,(如果它总是:
),你可以使用这个:
NSArray *substrings = [myString componentsSeparatedByString:@":"];
NSString *first = [substrings objectAtIndex:0];
NSString *second = [substrings objectAtIndex:1];
that will split your string into two pieces, and give you the array with each substring
这会将您的字符串分成两部分,并为您提供每个子字符串的数组
回答by iAkshay
Here is an extension of zaph's answer that I've implemented successfully.
这是我已成功实施的 zaph 答案的扩展。
-(NSString*)stringBeforeString:(NSString*)match inString:(NSString*)string
{
if ([string rangeOfString:match].location != NSNotFound)
{
NSString *preMatch;
NSScanner *scanner = [NSScanner scannerWithString:string];
[scanner scanUpToString:match intoString:&preMatch];
return preMatch;
}
else
{
return string;
}
}
-(NSString*)stringAfterString:(NSString*)match inString:(NSString*)string
{
if ([string rangeOfString:match].location != NSNotFound)
{
NSScanner *scanner = [NSScanner scannerWithString:string];
[scanner scanUpToString:match intoString:nil];
NSString *postMatch;
if(string.length == scanner.scanLocation)
{
postMatch = [string substringFromIndex:scanner.scanLocation];
}
else
{
postMatch = [string substringFromIndex:scanner.scanLocation + match.length];
}
return postMatch;
}
else
{
return string;
}
}