【问题标题】:The problem of analyzing a string and searching解析字符串和搜索的问题
【发布时间】:2020-12-18 23:29:46
【问题描述】:

我想编写代码,从用户那里获取一串文本,并使用 .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;
}

【问题讨论】:

  • while(string txt != NULL) { if(txt.find(" ")) ++word; } -- 如果有多个连续的空格怎么办?即使您修复了代码的string txt != NULL 部分,您也会遇到问题。
  • std::string::find 返回字符串中的位置,如果找到的话;否则返回std::string::npos。这两个值都可以视为true;但是,如果字符串以空格开头,则位置将为 0,计算结果为 false。

标签: c++ visual-c++ c++17


【解决方案1】:

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

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&gt;&gt; 跳过空格:

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

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

【讨论】:

    猜你喜欢
    • 2011-01-30
    • 1970-01-01
    • 2011-12-18
    • 1970-01-01
    • 1970-01-01
    • 2013-04-08
    • 2013-03-18
    • 2013-02-18
    • 1970-01-01
    相关资源
    最近更新 更多