比较词语的两个字符串 [英] Compare words in two strings

查看:110
本文介绍了比较词语的两个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了两个字符串。用户可以填补他们。

I have made two strings. User can fill them both.

char text[200];
char text2[200];  

我需要找到两个字符串类似的话。例如,

I need to find similar words from both strings. For example,

文本=我在这里为我所有的生活

Text= I am here for all my life

文本2 =他们在这里赢得我们所有人

Text2= They are here to win us all

我需要程序找到像'这里','所有'类似的话。
我想这样的,但它没有找到的所有单词。

I need to program finds similar words like 'here','all'. I tried like this but it don't found all words.

if(strstr(text,text2) != NULL)

然后printf的,但我认为它不是正确的事情。

and then printf but i think it isnt the right thing.

推荐答案

我觉得这是你想要什么:

I think this is what you want:

char text[] = "I am here for all my life";
char text2[] = "They are here to win us all";

char *word = strtok(text, " ");

while (word != NULL) {
    if (strstr(text2, word)) {
        /* Match found */
        printf("Match: %s\n", word);
    }
    word = strtok(NULL, " ");
}

它使用的strtok()通过文字阅读句子单词,的strstr()来搜索在其他句子对应的单词。请注意,这不是很有效,如果你有数据大块大块的,你必须考虑一个更聪明的算法。

It uses strtok() to read the sentence word by word, and strstr() to search for the corresponding word in the other sentence. Note that this is not very efficient, if you have big chunks of data you'll have to consider a smarter algorithm.

更新:

既然你不想匹配的嵌入式的话,的strstr()是对你很大帮助没有。而不是使用的strstr()的,你必须使用一个自定义函数。事情是这样的:

Since you don't want to match embedded words, strstr() is not of much help for you. Instead of using strstr(), you have to use a custom function. Something like this:

#include <ctype.h>
int searchword(char *text, char *word) {
    int i;

    while (*text != '\0') {
        while (isspace((unsigned char) *text))
            text++;
        for (i = 0; *text == word[i] && *text != '\0'; text++, i++);
        if ((isspace((unsigned char) *text) || *text == '\0') && word[i] == '\0')
            return 1;
        while (!isspace((unsigned char) *text) && *text != '\0')
            text++;
    }

    return 0;
}

另外code保持不变,但更换调用的strstr()通过这一新的函数的调用:

The other code stays the same, but replace the call to strstr() by a call to this new function:

char text[] = "I am here for all my life";
char text2[] = "They are here to win us all";

char *word = strtok(text, " ");

while (word != NULL) {
    if (searchword(text2, word)) {
        /* Match found */
        printf("Match: %s\n", word);
    }
    word = strtok(NULL, " ");
}

这篇关于比较词语的两个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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