iphone - Objective C 中的多个字符串替换

标签 iphone objective-c string

我知道这是错误的方法(因为它会出错),但你可以看到我正在尝试做什么:

NSString *urlTerm = [terms stringByReplacingOccurrencesOfString:@" " withString:@"+"];
NSString *urlTerm = [terms stringByReplacingOccurrencesOfString:@"  " withString:@""];
NSString *urlTerm = [terms stringByReplacingOccurrencesOfString:@"&" withString:@""];
NSString *urlTerm = [terms stringByReplacingOccurrencesOfString:@"'" withString:@""];
NSString *urlTerm = [terms stringByReplacingOccurrencesOfString:@"-" withString:@""];
NSString *urlTerm = [terms stringByReplacingOccurrencesOfString:@"_" withString:@""];

我有一个名为“term”的搜索词,想要将清理后的版本输出到“urlTerm”中?

最佳答案

-stringByReplacingOccurrencesOfString: 返回一个新字符串。原始字符串terms不会受到此函数的影响。 即使terms会受到影响,第二条语句也永远不会成功,因为所有空格都已经在第一条语句中变成了+,并且没有留下双空格。 (好吧,原来“双空格”是一个制表符。:| )

你可以使用

NSString* urlTerm = terms;
urlTerm = [urlTerm stringByReplacingOccurrencesOfString:@"\t" withString:@""];
urlTerm = [urlTerm stringByReplacingOccurrencesOfString:@"&" withString:@""];
urlTerm = [urlTerm stringByReplacingOccurrencesOfString:@"'" withString:@""];
urlTerm = [urlTerm stringByReplacingOccurrencesOfString:@"-" withString:@""];
urlTerm = [urlTerm stringByReplacingOccurrencesOfString:@"_" withString:@""];
urlTerm = [urlTerm stringByReplacingOccurrencesOfString:@" " withString:@"+"];

关于iphone - Objective C 中的多个字符串替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4182545/

相关文章:

ios - 使用蒙版裁剪图像

iphone - iPhone两次之间的时差

iphone - 获取 iPhone 上当前的系统音量级别

c# - 当来自字符串时,SqlXml 删除 XML header

php - 如何从 PHP 中的括号之间获取所有内容?

iphone - iPhone 中的 HTTP 身份验证

iphone - 重新请求访问设备联系人

ios - 应用程序更新时的 NSUserDefaults 行为

objective-c - 从现有指针构建指针数组

c++ - 数学运算符未注册为输入?