获取 NSString 中的相似字符
我正在寻找一种可以从 NSString 中提取相同单词的方法。这听起来很令人困惑,但这就是我正在寻找的内容:
String 1: @"Word 4"
字符串 2:@"Word 5"
->结果:@"Word"
as NSString(因为4和5不一样,所以它们被删除,然后是空格,因为,好吧,它没用)
这个函数还需要去掉单词而不是字符,因此输入结果将如下所示:
String 1: @"Word Abcdef"
字符串 2:@"Word Abcedf"
->结果:@"Word"
而不是 @"Word Abc"
-- 或 --
字符串 1:@"Word 12"
字符串 2:@"Word 15"
->结果:@"Word"
而不是 @"Word 1"
I'm looking for a method that can extract the same words from NSStrings. This sounds confusing, but here's what I'm looking for:
String 1: @"Word 4"
String 2: @"Word 5"
-> Result: @"Word"
as NSString (since 4 and 5 are not the same, they are removed, and then the space because, well, it's useless)
This function also needs to strip out words instead of characters, so an input would result in something like this:
String 1: @"Word Abcdef"
String 2: @"Word Abcedf"
-> Result: @"Word"
instead of @"Word Abc"
-- OR --
String 1: @"Word 12"
String 2: @"Word 15"
-> Result: @"Word"
instead of @"Word 1"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我会用空白字符(如 ComponentsSeparatedByString:)分割两个字符串,然后使用循环将一个数组中的每个单词与另一个数组进行比较。如果这个词出现在两个数组中,我会将其添加到 NSMutableArray 中,最后使用 ComponentsJoinedByString: 来获取最终的字符串。
希望这有帮助。
i would split both strings by white space characters like componentsSeparatedByString:, then use a loop to compare each word from one array to the other. if the word appears both arrays I would add it to an NSMutableArray, and at the end use componentsJoinedByString: to get your final string.
Hope this helps.
将字符串拆分为单词数组,然后迭代该数组以提取相似的单词。
Split the strings into an array of words and then iterate through the array to extract the similar words.
我采纳了 @Moszi 和 @Carters 的想法,并缩短了代码以实现最高效率,这是我迄今为止发现的有效方法:
我还确保当一个字符串比另一个字符串包含更多单词时不会出现错误。
I took both @Moszi and @Carters ideas and shortened the code for the most efficiency, and here's what I've found to work so far:
I made also made sure not to get an error when one string has more words than another.