ios - 从 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:@""];
这将给出“最喜欢的马是否赢得了比赛”
如何在不删除部分单词留下碎片的情况下干净地删除多个单词?
感谢您的任何建议。
解决方案
// 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
。
推荐阅读
- android - 将 Json 和标头发布到 REST api KOTLIN
- java - Accept-Language 标头和 ResourceBundle 之间缺少功能
- react-hooks - 输入值数组上的 useState 移除焦点
- java - 内存问题时如何修改大型 Excel 文件
- sql - 自表连接上的 SQL
- javascript - Cpanel 上的 Javascript AJAX POST 出现 500 内部服务器错误
- asp.net-mvc - 在 asp.net mvc 的数据库中插入下拉列表值
- excel - 比较两列并根据参考列的顺序输出新列
- c# - Private Set 属性未保留其新值
- kubernetes - 从 Pod 调用 Kubernetes API 时收到错误消息