如何在两个单独的字符串中查找匹配的单词? [英] How to find matching words in two separate strings?

查看:191
本文介绍了如何在两个单独的字符串中查找匹配的单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有两个单独的字符串,我们需要检索数组中匹配(在这些字符串中)的所有单词。此匹配也应不区分大小写。实现这一目标的最有效方法是什么。

If there are two separate strings, we need to retrieve all words that are matching (in those strings), in an array. also this matching should be case insensitive. What will be the most efficient way to achieve this.

例如:

NSString *s1 = @"Hello there, I want to match similar words.";  
NSString *s2 = @"Do you really want to match word, hello?";  

结果数组应该包含,hello,want,to,match

我经历了很多问题和回复在网上像正则表达式匹配一条没有的线包含一个单词?,但没有,找到所需的解决方案。

I went through many questions and, responses over the net like Regular expression to match a line that doesn't contain a word?, but didn't, find solution needed.

推荐答案

你可以使用 NSMutableSet for this ..

You can use NSMutableSet for this..

    NSString *s1 = @"Hello there, I want to match similar words.";  
    NSString *s2 = @"Do you really want to match word, hello?"; 

    NSArray *components = [s1 componentsSeparatedByString:@" "];
    NSArray *components1 = [s2 componentsSeparatedByString:@" "];
    NSLog(@"%@",components);
    NSLog(@"%@",components1);

    NSMutableSet *resultSet = [NSMutableSet setWithArray:components1];
    NSSet *setA = [NSSet setWithArray:components];
    [resultSet intersectSet:setA];
    NSArray *result = [resultSet allObjects];
    NSLog(@"%@",result);

此解决方案适用于您,如果您的句子中没有任何标点符号..如果你想要使用带有标点符号的句子来删除句子中的所有标点符号。

This Solution will work for you, If you don't have any punctuations in the sentences.. If you want sentences with punctuations to work just remove all the punctuations in your sentences.

这篇关于如何在两个单独的字符串中查找匹配的单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆