【问题标题】:How to keep track of distinct chars and words?如何跟踪不同的字符和单词?
【发布时间】:2018-03-20 03:34:32
【问题描述】:

尝试编写一个函数来分析输入文件并输出诸如不同字符、每个单词的平均长度和总单词数等信息。我无法弄清楚如何跟踪字符串中的不同字符。例如以下行:

成为或不成为,这是个问题。

应返回 10 个总字数、12 个不同字符和 3.2 个平均字长。

这是我到目前为止的代码:

void fileInfo(const string& fileName)
{
     ifstream in(fileName);
     if (in.fail())
     {
          cout << "Error, bad input file.";
     }

     string line = "";
     int wordTotal = 0;
     while (getline(in, line))
     {
          istringstream ss(line);
          string word = "";
          while (ss >> word)
          {
                wordTotal++;
                for (size_t i = 0, len = word.size(); i < len; i++)
                {
                    if (word.at(i))
                }
          }
     {






}  

【问题讨论】:

  • 由于std::set 不存储重复项,您可以使用std::set&lt;char&gt; 并将单词中的每个字符插入到集合中。

标签: c++ while-loop char istream


【解决方案1】:

一种解决方案是使用std::unordered_set&lt;char&gt; 来存储每个单词的字母。由于 unordered_set 不存储重复项,因此您最终会得到一组不同的字母。

其次,您只想计算字母字符,而不是标点符号或数字,然后再放入一组中。因此,您需要过滤每个字符以确保它是字母。

void fileInfo(const string& fileName)
{
   std::unordered_set<char> cSet;
   //...
   while (ss >> word)
   {
       wordTotal++;
       for (auto v : word)
       {
           if (std::isalpha(v))
              cSet.insert(std::tolower(v));
       }
   }    
   //...
}

Live Example

仅当单词是字母时才会插入到集合中。另请注意,插入的字母是小写版本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-17
    • 2015-09-20
    • 1970-01-01
    • 2015-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多