分析字符串和搜索的问题

问题描述

我想编写代码,从用户那里获取一串文本,并使用 .find () 函数显示字符数和单词数。然后从用户那里获取一个词并搜索文本并显示该词的位置。我现在有麻烦了,请帮帮我。

#include<iostream>
#include <cctype>
#include<string>
#include<cstring>
using namespace std;

int main()
{   char quit;
    int word=0;
    string txt;
    cout << "Enter a string: ";
    getline(cin,txt);
    cout << "The number of characters in the string is:" << txt.length() << endl;
    while(string txt != NULL)
    {   if(txt.find(" "))
            ++word;
    }
    cout<<"wors is "<<word;
    while(quit!='q')
    {

        cout<<"wors is ";
        cin>>search;
        cout<<"Enter(c)if you want to continue,and enter(q)if you want quic:";
        cin>>quit;
    }
    return 0;
}

解决方法

这是一个提取单词的示例。还有很多其他的方法。

static const char end_of_word_chars[] = "!?.,:\t";
//...
std::string::size_type previous_position = 0;
std::string::size_type position = txt.find_first_of(end_of_word_chars);
while (position != std::string::npos)
{
  std::string word = txt.substr(previous_position,position - previous_position);
  std::cout << word << "\n";
  previous_position = txt.find_first_of(position + 1);
  position = txt.find_first_not_of(end_of_word_chars);
}

上面的代码使用了一个“词尾字符”数组,来表示一个词的结尾。从头开始搜索字符串 txt 以查找单词结尾字符集中第一个字符的位置。在 while 循环中,跳过空格或非单词字符。并找到下一个“词尾”字符的位置,循环可能会再次重复。

编辑 1:字符串作为流
另一种方法是将 txt 视为字符串流并使用 operator>> 跳过空格:

std::istringstream text_stream(txt);
std::string word;
while (text_stream >> word)
{
    std::cout << word << "\n";
}

上述代码片段的一个问题是它没有考虑不是空格或制表符的词尾字符。例如,在文本“Yes. I'm Home.”中,句点作为“word”的一部分包含在内,例如“Yes”。和“家”。