ios 如何在特定的 NSString 之后从 NSString 中删除字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9717723/
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
how to remove characters from NSString after specific NSString
提问by user968597
I am having a string as follows
我有一个字符串如下
NSString str1 = @"Hello your bal = 68094";
and I want to remove all characters after "="symbol encounters in string.
我想在字符串中遇到“=”符号后删除所有字符。
Can any one give me the solution for this?
任何人都可以给我解决这个问题吗?
回答by Ilanchezhian
Try the following solution:
尝试以下解决方案:
NSString *str1 = @"Hello your bal = 68094";
NSRange range = [str1 rangeOfString:@"="];
if (range.location != NSNotFound) {
NSString *newString = [str1 substringToIndex:range.location];
NSLog(@"%@",newString);
} else {
NSLog(@"= is not found");
}
or
或者
NSString *str1 = @"Hello your bal = 68094";
NSRange range = [str1 rangeOfString:@"="];
if (range.location != NSNotFound) {
NSString *newString = [str1 substringWithRange:NSMakeRange(0, range.location)];
NSLog(@"%@",newString);
} else {
NSLog(@"= is not found");
}
Update for @geekay_gk: If you are sure that you would have 2 "=" in your string, then
更新@geekay_gk:如果你确定你的字符串中有 2 个“=”,那么
NSString *str1=@"Hello your balance = 60094 and your id = rt456";
NSRange range = [str1 rangeOfString:@"=" options: NSBackwardsSearch];
NSString *newString = [str1 substringFromIndex:(range.location+1)];
NSLog(@"%@",newString);
If it contains whitespace, it would be better to trim the string.
如果它包含空格,最好修剪字符串。
回答by Novarg
Maybe not the best solution, but here it is:
也许不是最好的解决方案,但它是:
NSString *str1=@"Hello your bal = 68094";
NSArray *tempArray = [str1 componentsSeparatedByString:@"="];
str1 = [tempArray objectAtIndex:0];
NSLog(@"%@", str1);
Output:
输出:
2012-03-15 11:21:01.249 TestApp[1539:207] Hello your bal
Hope it helps
希望能帮助到你