【问题标题】:Count number of occurrences in string c++?计算字符串c ++中出现的次数?
【发布时间】:2016-10-26 22:12:54
【问题描述】:

我习惯了 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:1次

d:2次

f:1次

小时:1次

我:1229148993次

j:73次

l: 2 次​​p>

n:2次

p:1次

r:1次

v:1次

您能给我的任何帮助将不胜感激。尽管这是简单的东西,但我是一个 java 傻瓜。 -_-

【问题讨论】:

  • int counts[26] = {0};
  • 初始化counts。目前你不知道内存中有什么,而且通常 C++ 不会为你初始化存储,因为你相信如果你关心值是什么,你就会设置它。 int counts[26] = {0};
  • int map[121];你可以这样做。如果你是字母表都是 7 位字符
  • 确实,这是与 Java 的区别之一。那里一切都被初始化,默认为0
  • @self:对,因为 2^7 是 121...

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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      我不知道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;
      }
      

      【讨论】:

      • 你忽略了EBCDIC。不用担心。每个人都这样做。
      • 在调用 isalpha 时会触发未定义的行为。您应该进行范围更改,然后强制转换为 unsigned int
      • @self:您是否暗示isalpha 的 cppreference 文档不正确?
      • 我只是初始化了数组。我什至没有看代码的其他部分
      猜你喜欢
      • 2023-02-04
      • 2011-04-21
      • 2011-05-13
      • 2014-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多