从 Swift 或 Objective-C 中的字符串中删除确切的词组

remove exact word phrase from string in Swift or Objective-C

我想从 Swift 或 Objective-C 中的字符串中删除单词的精确组合,而不删除单词的一部分。

您可以通过将字符串转换为数组来从字符串中删除单个单词:

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:@""];

这会给 "Did the favo horse win the race"

如何在不删除部分单词而留下片段的情况下干净地删除多词项?

感谢您的任何建议。

您还可以考虑前导 space 并将整个匹配替换为单个 space:

str = [str stringByReplacingOccurrencesOfString:@" red horse " withString:@" "];

或者,您可能需要调整此示例,您可以只使用正则表达式 - 这是它们设计的目的,语法在 Swift[=12= 中很好]

// 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([=10=]) }.joined(separator: " ")

// result = "Did the favored win the race?"

此方法的注意事项是它会删除原始字符串中任何位置的确切单词。如果您希望结果仅删除以确切顺序出现的单词,则只需在 replacingOccurrencesOf.

的参数前面使用 space

如果您想删除一些单词,请尝试使用此扩展程序:

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

输出:

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

输出:

result: Did the favored win the race?

不要忘记在要删除的词中包含 space...希望对您有所帮助