Skip to content

Latest commit

 

History

History
85 lines (59 loc) · 1.8 KB

File metadata and controls

85 lines (59 loc) · 1.8 KB

C++ 程序:查找字符串中字符的频率

原文: https://www.programiz.com/cpp-programming/examples/frequency-character

在此示例中,将同时检查字符的出现频率(字符串对象和 C 样式字符串)。

要理解此示例,您应该了解以下 C++ 编程主题:


在此示例中,计算字符串对象中字符的频率。

为此,可使用size()函数查找字符串对象的长度。 然后,迭代for循环,直到字符串结尾。

在每次迭代中,都会检查字符的出现,如果找到,字符count的值将增加 1。


示例 1:查找字符串对象的字符频率

#include <iostream>
using namespace std;

int main()
{
    string str = "C++ Programming is awesome";
    char checkCharacter = 'a';
    int count = 0;

    for (int i = 0; i < str.size(); i++)
    {
        if (str[i] ==  checkCharacter)
        {
            ++ count;
        }
    }

    cout << "Number of " << checkCharacter << " = " << count;

    return 0;
} 

输出

Number of a = 2

在下面的示例中,循环迭代直到遇到空字符**'\ 0'**。 空字符表示字符串的结尾。

在每次迭代中,都会检查字符的出现。


示例 2:查找 C 样式字符串中字符的频率

#include <iostream>

using namespace std;
int main()
{
   char c[] = "C++ programming is not easy.", check = 'm';
   int count = 0;

   for(int i = 0; c[i] != '\0'; ++i)
   {
       if(check == c[i])
           ++count;
   }
   cout << "Frequency of " << check <<  " = " << count;
   return 0;
}

输出

Number of m = 2