C ++在句子中查找单词 [英] C++ Find word in sentence

查看:532
本文介绍了C ++在句子中查找单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个任务在一个语句(更像是一行字符)中找到EYE这个词,例如: EYEYECARASDFG 。正如你所看到的那样,EYE这个词有两次出现,重叠在一起。我假设 cout 在句子中出现EYE这个词多少次。我写了一些如下所示的代码:

  #include< iostream> 
#include< string>

使用namespace std;

字符串句子;

int main()
{
int i = 0;
cin>>句子;
$ b $ while()
{
if(std :: string :: npos!= sentence.find(EYE))
{
i ++ ;
}
}


cout<一世;

$ / code>

现在如果没有循环,它发现在句子中的眼睛,它有点作品。所以我认为,为了计算重叠,并使代码运行,直到它结束,我需要循环它。所以我虽然while循环将是最好的,但我不知道如何循环,什么要放在的括号,而循环

解决方案

首先中的条件,而是必需的。如果你想循环使用 true 作为你的语句。作为第一稿,试着用蛮力做出来。只要检查你的句子的每个3个字母的子字符串,如果等于EYE。这将是一个循环和3个条件或2个循环和1个条件。然后阅读一些文本搜索算法,例如 KMP



如果你只是想让这段代码运行,使用下面的代码:

  int pos = 0; 
while(true){
pos = sentence.find(EYE,++ pos);
if(pos!= std :: string :: npos){
i ++;
} else else break;
}


I've got a task to find the word "EYE" in a sentence (more like just line of chars) such as: EYEYECARASDFG. As you can see, the word "EYE" is there twice, overlapping each other. I am suppose to cout how many times the word "EYE" occurs in the sentence. I wrote some code that looks like this:

#include <iostream>
#include <string>

using namespace std;

string sentence;

int main()
{
    int i = 0;
    cin >> sentence;

    while()
    {
        if (std::string::npos != sentence.find("EYE"))
        {
            i++;
        }
    }


    cout << i;
}

Now without the while loop, it finds the EYE in the sentence and it kinda works. So I though, to count with the overlapping and make the code running until it hits the end, I need to loop it. So I though the while loop would be the best, but I don't know how to loop it, what to put into the brackets for while loop

解决方案

First of all condition in while is required. If you want infinite loop use true as your statement. As a first draft, try to make it with "brute force". Just check every 3 letters substring of your sentence if equals "EYE". It will be one loop and 3 conditions or 2 loops and 1 condition. Then read about some text search algorithm e.g KMP.

If you just want to make this code run use following coed:

int pos = 0;
while(true) { 
    pos =  sentence.find("EYE", ++pos);
    if (pos != std::string::npos) {
        i++;
    } else break;
 }

这篇关于C ++在句子中查找单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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