数字有困难

Trouble counting words

本文关键字:数字      更新时间:2023-10-16

我遇到了关于字数统计程序的问题。我希望程序能够告诉我给定字符串中有多少个单词、行、字符、唯一行和唯一单词。但是,我不断遇到有关此的问题。有人可以帮我,特别是关于空格字符吗?

#include <iostream>
using std::cin;
using std::cout;
using std::endl;
#include <string>
using std::string;
#include <set>
using std::set;
unsigned long countLines(const string& s)
{
int nl = 0;
for(int x =0; x<s.size(); x++)
{
    if(s[x] == "")
nl++;
}
return nl;
}
unsigned long countWords(const string& s)
{
    int nw = 0;
    char ws = " ";
    for (int x = 0; x<s.size(); x++)
    {
        if (s[x] == ws)
        {
            nw++;
        }
    }
    return nw;
}
unsigned long countChars(const string& s)
{
int nc = 0;
for (int x = 0; x < s.size(); x++)
{
    if ( s[x] != " ")
    {
        nc++;
    }
}
return nc++;
}
unsigned long countuline(const string& s, set<string>& wl)
{
wl.insert(s);
return wl.size(s);
}
unsigned long countuwords(const string& s, set<string>& wl)
{
int nuw = 0;
char ws = " ";
wl.insert(s);
for (int x = 0; x<s.size(); x++)
{
    if (s[x] == ws)
    {
        nuw++;
    }
}
return nuw;
}
int main()
{
string line;
while (getline(cin,line))
{
    cout << countLines(line) << "t" << countWords(line) << "t" << countChars(line) << endl;
}
return 0;
}

如果性能不是问题,您可以将整个字符串放在流中并读取它。默认情况下,字符串流读取单词(使用空格作为拆分字符):

unsigned int count_words(const std::string& str)
{
    std::stringstream ss( str );
    unsigned int count = 0;
    std::string aux_string;
    while( ss >> aux_string )
         count++;
    return count;
}

countLines 始终返回 1,并且不使用字符串 s。您始终将 nl 设置为零并在返回之前将其递增 1。

    int nl = 0;

数词,这句话"你好世界!"的结果是什么?