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

时间:2016-10-26 22:12:55

标签: c++ arrays string function for-loop

我习惯于java,尽管知道理论,但仍然在努力克服C ++的基本语法。我有一个函数试图计算字符串中出现的次数,但输出是一个奇怪的选项卡。

这是我的代码:

#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

你进入了迪伦

b:1次

c:1Times

d:2次

f:1次

h:1次

i:1229148993Times

j:73次

l:2次

n:2次

p:1Times

r:1Times

v:1Times

您可以给予我任何帮助将不胜感激。尽管这很简单,但我还是个傻瓜。 -_-

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:2)

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

答案 2 :(得分:1)

我不了解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;
}
相关问题