首页 > 解决方案 > 从 Swift 或 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:@""];

这将给出“最喜欢的马是否赢得了比赛”

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

感谢您的任何建议。

标签: iosobjective-cswiftnsstringnsarray

解决方案


// 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?"

这种方法的警告是它会删除原始字符串中任何位置的那些确切单词。如果您希望结果仅删除以该确切顺序出现的单词,则只需在参数前面使用一个空格 for replacingOccurrencesOf


推荐阅读