计数c++字符串中出现的次数

Count number of occurrences in string c++?

本文关键字:c++ 字符串 计数      更新时间:2023-10-16

我已经习惯了java,尽管知道c++的基本语法,但还是很纠结。我有一个函数,它试图计算字符串中出现的次数,但输出是一个tab有点奇怪。

下面是我的代码:
#include <cstdlib>
#include <iostream>
#include <cstring>
/*
 main 
 * Start 
 * prompt user to enter string 
 * call function 
 * stop 
 * 
 * count
 * start 
 * loop chars 
 * count charts 
 * print result
 * stop

 */
 using namespace std;
void count(const char s[], int counts[]);
int main(int argc, char** argv) {
int counts[26];
char s[80];
//Enter a string of characters
cout << "Enter a string: "; // i.e. any phrase
cin.getline(s,80);
cout << "You entered " << s << endl;
count(s,counts);
//display the results
for (int i = 0; i < 26; i++)
if (counts[i] > 0)
  cout  << (char)(i + 'a') << ": " << counts[i] << "Times " << endl;
return 0;
}
void count(const char s[], int counts[]){
for (int i = 0; i < strlen(s); i++)
{
char c = tolower(s[i]); 
if (isalpha(c))
    counts[c - 'a']++;
}
}

输出如下:

输入字符串:Dylan

你输入了Dylan

b: 1Times

c: 1Times

d: 2Times

f: 1Times

h: 1Times

i: 1229148993Times

j: 73Times

l: 2Times

n: 2Times

p: 1Times

r: 1Times

v: 1Times

如果你能给我任何帮助,我将非常感激。虽然这是简单的东西,但我是一个java迷。_——

您的counts未初始化。您需要首先将所有元素设置为0。

您需要将计数向量归零。试一试counts[26]={0};

我不知道java,但是你必须在C/c++中初始化变量。下面是你的代码:

#include <cstdlib>
#include <iostream>
#include <cstring>
using namespace std;
void count(const char s[], int counts[]){
    for (int i = 0; i < strlen(s); i++)
    {
        char c = tolower(s[i]); 
        if (isalpha(c))
            counts[c - 'a']++;
    }
}
int main(int argc, char** argv) {
    int counts[26];
    char s[80];
    //Enter a string of characters
    cout << "Enter a string: "; // i.e. any phrase
    cin.getline(s,80);
    for(int i=0; i<26; i++)
        counts[i]=0;
    cout << "You entered " << s << endl;
    count(s,counts);
    //display the results
    for (int i = 0; i < 26; i++)
        if (counts[i] > 0)
            cout  << (char)(i + 'a') << ": " << counts[i] << "Times " << endl;
    return 0;
}