数字有困难
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;
数词,这句话"你好世界!"的结果是什么?
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 检查输入是否不是整数或数字
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 如何用数字处理log(0)
- 最高有效数字侧的第N位
- 如何获取一个数字的前3位
- 查找最接近的大于当前数字的数字的索引
- 找到两对数字,使它们的乘积的绝对差最小化
- 我想做一个彼此不同但重复出现的数字
- 将数字转换为字母(例如:123 转换为一二三)
- C++如何计算用户输入的数字中的偶数位数
- 如何在C++中确定文本文件中的元素是字符还是数字
- 打印数字图案
- C++问题:用户认为数字1-100,程序提出问题不超过6次即可得到答案。无法正确
- 如何检查一个c++字符串中有多少相同的字符/数字
- 求出有多少个数字是完美平方,而sqrt()是L,R范围内的素数
- 将数字打印成文字
- 当使用比格式支持的精度更高的精度来显示数字时,会写出什么数据
- 在将数字随机生成为数组期间从内存输出随机数的数组