C++计算字符串中的字符数
C++ count chars in a string
我需要计算输入句子中输入字符的数量。我离得很近,但是我不断收到此错误:
countchar.cpp:19:19: error: empty character constant
countchar.cpp: In function â:
countchar.cpp:26:75: error: could not convert â from â to â
#include <string>
#include <fstream>
#include <iostream>
#include <algorithm>
using namespace std;
void WordOccurenceCount(string, int);
int main()
{
char character;
string sentence;
char answer;
string cCount;
while(1) {
cout << "Enter a char to find out how many times it is in a sentence: ";
cin >> character;
cout << "Enter a sentence and to search for a specified character: ";
cin >> sentence;
if(character == '' || sentence == "" )
{
cout << "Please enter a valid answer:n";
break;
}
else {
cCount = WordOccurenceCount(sentence.begin(), sentence.end(), character);
cout << "Your sentence had" << cCount << character
<< "character(s)";
}
cout << "Do you wish to enter another sentence (y/n)?: ";
cin >> answer;
if (answer == 'n'){
break;
}
}
return 0;
}
int WordOccurrenceCount( string const & str, string const & word )
{
int count;
string::size_type word_pos( 0 );
while ( word_pos!=string::npos )
{
word_pos = str.find(word, word_pos );
if ( word_pos != string::npos )
{
++count;
// start next search after this word
word_pos += word.length();
}
}
return count;
谁能伸出援手?
没有空字符这样的东西。
只是写
if (sentence == "")
{
cout << "Please enter a valid answer:n";
break;
}
此代码的问题: 1. C++不取空字符:if(character == '')
2. 函数WordOccurrenceCount
中的参数与您的声明不匹配。 3.sentence.begin()
是String_iterator类型,不能转换为字符串。(如您的WordOccurrenceCount
函数所期望的那样) 4. 同样,sentence.end
也是String_iterator类型,不能转换为 int(如函数声明所预期)或字符串(如函数定义所预期)。
计数后(请将来以某种方式标记错误的行),问题之一是这一行:
if(character == '' || sentence == "" )
在 C++(和 C)中,不能有空字符文本。
当您阅读character
并且没有输入任何内容时,您会得到换行符,因此第一次检查应该是character == 'n'
。
至于字符串,有一个非常简单的方法来检查字符串是否为空: std::string::empty
:
sentence.empty()
所以完整的条件应该是
if (character == 'n' || sentence.empty()) { ... }
至于其他错误,确实存在多个错误:首先,您声明WordOccurenceCount
接受两个参数,一个字符串和一个整数。然后使用三个参数调用它,其中没有一个参数属于正确的类型。
那么在WordOccurenceCount
的定义中,与声明相比,你有不同的参数。
最后,如果你想计算某个字符在字符串中出现的时间,那么你可能需要查看C++中可用的标准算法,尤其是std::count
:
std::string sentence;
std::cout << "Enter a sentence: ";
std::getline(std::cin, sentence);
char character;
std::cout << "Enter a character to be found: ";
std::cin >> character;
long count = std::count(std::begin(sentence), std::end(sentence), character);
相关文章:
- 我的字符计数代码计算错误.为什么
- 如何计算常量字符**中的总字符数?
- 我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置
- C++理解计算字符变量的问题
- 计算在同一位置至少包含一个常用字符的不同字符串对
- 如何计算QString开头的重复字符?
- 如何计算特定字符前面的字符数
- 从文件中找出字符'a',然后计算字符出现的行数
- 当 NUL 字符被定义为字符串的一部分时,为什么 strlen() 不计算终止 NUL 字符的字节?
- 计算两个字符序列
- 如何计算 3d 数组中的索引值在内存中的位置?如何计算字符**中的索引值在内存中的位置?
- 我正在尝试创建一个布尔函数,该函数计算字符并在字符为"()*-+"时返回 true
- 计算字符串中字符的出现次数时出错
- 如何使用 ASCII 转换使用字符堆栈计算后缀表达式
- 动态计算 unicode 字符
- C++ 从文件中读取字符,计算每个字符并进行排序
- C++ std::string 中是否有任何函数可以计算两个字符串的相同起始字符的总数或任何最佳方法
- 如何有效地计算字母字符
- 你如何计算文件中的字符
- 如何计算C++字符数组中的单词