0

无论如何显示字符 s 在字符串中出现 5 次是否有任何函数可以对字符进行排序,而不是向我们显示字符在字符串中出现 5 或 6 次。

#include<iostream>
#include<string>
int main(){
using namespace std;
string a="hello how are you"
//now i want to show the l character appears several time.
//and i need help here.

system("pause");
}
4

3 回答 3

3

您可以使用std::count

int lcount = std::count(a.begin(), a.end(), 'l');
于 2013-10-08T10:58:18.040 回答
2

只需使用指针继续计数,直到达到 nul 字符,并在成功比较时继续增加整数。

#include<iostream>
#include<string>
int main(){
using namespace std;
string a="hello how are you";
char *p = &a[0];
int c = 0;
do
{   
    if(*p == 'l')
    c++;
}while(*p++);
cout << c;
}
于 2013-10-08T11:02:28.533 回答
1

你可以走过任何容器,包括一根绳子,然后用它做你喜欢的事。您可以计算每个字符的实例数。您可能需要考虑忽略空格。

std::string a("hello how are you");
std::map<char,int> count;
for(auto c : a)
{
    ++count[c];
}
于 2013-10-08T11:04:39.357 回答