[英]Count number of occurrences in string c++?
I'm used to java, and struggle with basic syntax of C++ despite knowing theory. 我已经习惯了Java,并且尽管了解理论,但仍在使用C ++的基本语法。 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 输入字符串:Dylan
You entered Dylan 您输入了Dylan
b: 1Times b:1次
c: 1Times c:1次
d: 2Times d:2次
f: 1Times f:1次
h: 1Times h:1次
i: 1229148993Times 我:1229148993次
j: 73Times j:73次
l: 2Times l:2次
n: 2Times n:2次
p: 1Times p:1次
r: 1Times r:1次
v: 1Times v:1次
Any help you can give me would be greatly appreciated. 您能给我的任何帮助将不胜感激。 Even though this is simple stuff, I'm a java sucker. 即使这很简单,我还是一个java傻瓜。 -_- -_-
Your counts
is uninitialized. 您的counts
尚未初始化。 You need to first set all of the elements to 0. 您需要首先将所有元素设置为0。
You need to zeros the counts vector. 您需要将计数向量清零。 Try counts[26]={0};
尝试counts[26]={0};
I don't know about java, but you have to initialize your variables in C/C++. 我不了解Java,但是您必须在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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.