简体   繁体   中英

Count number of occurrences in string c++?

I'm used to java, and struggle with basic syntax of C++ despite knowing theory. I have a function that is trying to count the number of occurrences in a string, but the output is a tab bit weird.

Here is my code:

#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']++;

}

}

Here is the output:

Enter a string: Dylan

You entered 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

Any help you can give me would be greatly appreciated. Even though this is simple stuff, I'm a java sucker. -_-

Your counts is uninitialized. You need to first set all of the elements to 0.

You need to zeros the counts vector. Try counts[26]={0};

I don't know about java, but you have to initialize your variables in C/C++. Here is your code working:

#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM