gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 17:46:06 25 4
gpt4 key购买 nike

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

这将使“最喜欢的马赢得比赛”

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

感谢您的任何建议。

最佳答案

// 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的参数前面使用空格。

关于ios - 在Swift或Objective-C中从字符串中删除确切的词组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61914432/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com