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

时间:2015-02-07 14:27:52

标签: c++ string frequency

我希望计算字符串中每个字母的频率。但是这给了我一个错误。 "字符串下标超出范围"
请告诉我这个代码有什么问题。

  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] != '\0' )    
            {
                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 ;
            }

3 个答案:

答案 0 :(得分:1)

在C ++之前11 std::string不能保证被\0终止(与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;
    }
}

答案 1 :(得分:0)

完全重写你的代码,希望你不介意,它现在有效:

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

      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]);
   }

答案 2 :(得分:0)

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

  

reference at(size_type pos);
  如果out_of_range

投掷pos >= size()

对于null终止符也是如此。因此,迭代std::string的正确方法是C ++ 11方式:

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

或C ++ 03方式:

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

在点击'\0之前,您无需走路。

第二个问题是终端循环:

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 ;
}
相关问题