如何在特定的NSString之后从NSString中删除字符

时间:2012-03-15 10:18:19

标签: ios nsstring

我有一个字符串如下

NSString str1 = @"Hello your bal = 68094";

我希望在“=”符号遇到字符串后删除所有字符。

任何人都可以为我提供解决方案吗?

2 个答案:

答案 0 :(得分:71)

尝试以下解决方案:

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

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

@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);

如果它包含空格,最好修剪字符串。

答案 1 :(得分:9)

也许不是最好的解决方案,但现在是:

NSString *str1=@"Hello your bal = 68094";
NSArray *tempArray = [str1 componentsSeparatedByString:@"="];
str1 = [tempArray objectAtIndex:0];
NSLog(@"%@", str1);

输出:

2012-03-15 11:21:01.249 TestApp[1539:207] Hello your bal 

希望有所帮助