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

问题描述 投票:0回答:2

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

哪个会给予“最喜欢的马赢得比赛”

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

感谢您的任何建议。

ios objective-c swift nsstring nsarray
2个回答
0
投票

您还可以考虑前导空格,并用单个空格替换整个比赛:

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

0
投票
// 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?"
© www.soinside.com 2019 - 2024. All rights reserved.