[英]remove exact word phrase from string in Swift or Objective-C
我想从 Swift 或 Objective-C 中的字符串中删除单词的精确组合,而不删除单词的一部分。
您可以通过将字符串转换为 arrays 来从字符串中删除单个单词:
NSString *str = @"Did the favored horse win the race?";
NSString *toRemove = @"horse";
NSMutableArray *mutArray = [str componentsSeparatedByString:@" "];
NSArray *removeArray = [toRemove componentsSeparatedByString:@" "];
[mutarr removeObjectsInArray:removeArr];
如果您不关心整个单词,也可以使用以下方法从另一个字符串中删除两个单词字符串:
str = [str stringByReplacingOccurrencesOfString:@"favored horse " withString:@""];
尽管您必须解决间距问题。
但是,这将在以下字符串上失败:
str = [str stringByReplacingOccurrencesOfString:@"red horse " withString:@""];
这将给出“最喜欢的马是否赢得了比赛”
如何在不删除部分单词留下碎片的情况下干净地删除多个单词?
感谢您的任何建议。
// Convert string to array of words
let words = string.components(separatedBy: " ")
// Do the same for your search words
let wordsToRemove = "red horse".components(separatedBy: " ")
// remove only the full matching words, and reform the string
let result = words.filter { !wordsToRemove.contains($0) }.joined(separator: " ")
// result = "Did the favored win the race?"
这种方法的警告是它会删除原始字符串中任何位置的那些确切单词。 如果您希望结果仅删除以该确切顺序出现的单词,则只需在参数前面使用空格来replacingOccurrencesOf
。
如果要删除某些单词,请尝试使用此扩展名:
extension String{
func replace(_ dictionary: [String: String]) -> String{
var result = String()
var i = -1
for (of , with): (String, String)in dictionary{
i += 1
if i<1{
result = self.replacingOccurrences(of: of, with: with)
}else{
result = result.replacingOccurrences(of: of, with: with)
}
}
return result
}
}
如何使用:
let str = "Did the favored horse win the race?"
let dictionary = ["horse ": "", "the ": ""]
let result = str.replace(dictionary)
print("result: \(result)")
Output:
result: Did favored win race?
一句话:
let str = "Did the favored horse win the race?"
let result = str.replacingOccurrences(of: "horse ", with: "", options: .literal, range:nil)
print("result: \(result)")
Output:
result: Did the favored win the race?
不要忘记在要删除的单词中包含空格...希望对您有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.