计算字符串中每个字母的频率

calculate frequency of each letter in a string

我想计算 string.But 中每个字母的频率,这给我一个错误。 "String subscript out of range"
请告诉我这段代码有什么问题。

  string text = "aaabbbbyyuuuuusdddddd" ;  //string of characters
            float arr[256] ,freq[6] ;
            int i=0 ;
            while(i<256)    // initializing a new array of 256 indexes
            {
                arr[i] = 0.00 ;
                i++ ;
            }
            i=0 ;
            int value ;
        // to increament the value within the indexes .index is the ASCII of the character in the string

            while(text[i] != '[=10=]' )    
            {
                value = text[i] ;
                arr[value] = arr[value] + 0.01 ;
                i++ ;
            }
            int j=0 ;
            i=0 ;
            while(i<256)
            {
                if(arr[i] != 0.00)
                {
                    freq[j] = arr[i] ;
                    j++ ;
                }
                i++ ;
            }
            j=0 ;
        //displaying the frequencies of each character 
            while(j<6)
            {
                cout << freq[j] << endl ;
            }

在 C++11 之前的版本中,std::string 不能保证被 [=12=] 终止(与 C 风格的 char[] 不同),感谢 Barry 的指点这个出来使用 std::string::size() 查找字符串的大小。

更好,尝试使用 std::map<char, size_t> 完成您的任务

#include <iostream>
#include <string>
#include <map>
#include <cstddef>

int main()
{
    std::string text = "aaabbbbyyuuuuusdddddd";
    std::map<char, std::size_t> freq;
    for(auto c: text)
    {
        if( freq.find(c) == freq.end())
            freq[c] = 1; 
        else
            ++freq[c];
    }

    for(auto elem: freq)
    {
        std::cout << elem.first << " -> " << elem.second << std::endl;
    }
}

完全重做你的代码,希望你不介意,它现在可以工作了:

   char string[100] = "aaabbbbyyuuuuusdddddd";
   int c = 0, count[26] = {0};
   while ( string[c] != '[=10=]' )
   {

      if ( string[c] >= 'a' && string[c] <= 'z' )
         count[string[c]-'a']++;
      c++;
   }

   for ( c = 0 ; c < 26 ; c++ )
   {
      if( count[c] != 0 )
         printf("%c occurs %d times in the entered string.\n",c+'a',count[c]);
   }

这里有两个问题。首先,虽然 std::string 空终止的(在 C++11 中是必需的,事实上在之前的大多数实现中),但您无法访问过去的 size()。如果你直接使用 string::at(),那么你会被击中:

reference at(size_type pos);
     Throws: out_of_range if pos >= size()

这对于空终止符来说是正确的。所以迭代 std::string 的正确方法是 C++11 方式:

for (value c : text) { ... }

或 C++03 方式:

for (size_t i = 0; i < text.size(); ++i) {
    value = text[i];
    ...
}

在达到 '[=21=] 之前,您无需步行。

第二个问题是你的终端循环:

j=0 ;
//displaying the frequencies of each character 
while(j<6)
{
    cout << freq[j] << endl ;
}

它不会终止。这是更喜欢使用 for 循环的一个很好的理由:

for (j=0; j < 6; ++j) 
//               ^^^^ you were missing this
{
    cout << freq[j] << endl ;
}