📌  相关文章
📜  程序计算字符串给定字符的出现

📅  最后修改于: 2021-05-30 02:07:28             🧑  作者: Mango

给定一个字符串和一个字符,任务是做一个计算字符串给定字符的出现的函数。

例子:

Input : str = "geeksforgeeks"
         c = 'e'
Output : 4
'e' appears four times in str.

Input : str = "abccdefgaa"
          c = 'a' 
Output : 3
'a' appears three times in str.
C++
// C++ program to count occurrences of a given
// character
#include 
#include 
using namespace std;
  
// Function that return count of the given 
// character in the string
int count(string s, char c)
{
    // Count variable
    int res = 0;
  
    for (int i=0;i


Java
// JAVA program to count occurrences
// of a character
  
class GFG
{
    // Method that return count of the given
    // character in the string
    public static int count(String s, char c)
    {
        int res = 0;
  
        for (int i=0; i


Python3
# Python program to count occurrences
# of a given character
  
# Method that return count of the 
# given character in the string
def count(s, c) :
      
    # Count variable
    res = 0
      
    for i in range(len(s)) :
          
        # Checking character in string
        if (s[i] == c):
            res = res + 1
    return res
      
      
# Driver code
str= "geeksforgeeks"
c = 'e'
print(count(str, c))
      
# This code is contributed by "rishabh_jain".


C#
// C# program to count occurrences
// of a character
using System;
          
public class GFG {
      
    // Method that return count of the given
    // character in the string
    public static int count(string s, char c)
    {
        int res = 0;
  
        for (int i = 0; i < s.Length; i++)
        {
              
            // checking character in string
            if (s[i] == c)
            res++;
        } 
          
        return res;
    }
      
    // Driver method
    public static void Main()
    {
        string str = "geeksforgeeks";
        char c = 'e';
          
        Console.WriteLine(count(str, c));
    }
}
  
// This code is contributed by Sam007.


PHP


输出:

4
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”