Comment compter les occurrences d’un caractère donné dans une chaîne

Les cordes sont un sujet très important dans la programmation des interviews. Il est sage de pratiquer quelques problèmes de programmation axés sur les chaînes avant vos interviews. Dans cet article, vous apprendrez à compter le nombre total d'occurrences d'un caractère dans une chaîne.

Exemples pour comprendre le problème

Exemple 1 : Soit la chaîne donnée « elle vend des coquillages au bord de la mer » et le caractère donné soit « s ».

str = "s il s ell s s s ea l' enfer s par le s s ea Hore"

ch = 's'

Il y a huit occurrences du caractère s dans la chaîne donnée.

Ainsi, la sortie est 8.

Exemple 2 : Soit la chaîne donnée « Il a lancé trois lancers francs » et le caractère donné « e ».

str = "H e e w thr thr ee ee fr jette"

ch = 'e'

Il y a six occurrences du caractère e dans la chaîne donnée.

Ainsi, la sortie est de 6.

Approche pour compter le nombre total d'occurrences d'un caractère dans une chaîne

Vous pouvez trouver le nombre total d'occurrences d'un caractère dans une chaîne en suivant l'approche ci-dessous :

  1. Initialisez une variable de compteur pour stocker le nombre total d'occurrences d'un caractère dans une chaîne.
  2. Parcourez la chaîne caractère par caractère.
  3. Si le caractère de la chaîne correspond au caractère donné, incrémente la valeur de la variable count.
  4. Enfin, retournez la variable compteur.

Programme C++ pour compter le nombre total d'occurrences d'un caractère dans une chaîne

Vous trouverez ci-dessous le programme C++ pour compter le nombre total d'occurrences d'un caractère dans une chaîne :

 // C++ program to count occurrences
// of a given character in a string
#include <iostream>
#include <string>
using namespace std;
// Function to count the occurrences of
// the given character in the string
int countOccurrences(string str, char ch)
{
// Counter variable
int counter = 0;
for (int i = 0; i < str.length(); i++)
{
// check if the given character matches
// with the character in the string
if (str[i] == ch)
{
// if the given character matches with
// the character in the string,
// increment the counter variable
counter++;
}
}
return counter;
}
// Driver code
int main()
{
string str1 = "she sells seashells by the seashore";
char ch1 = 's';
cout << "Input string 1: " << str1 << endl;
cout << "Character " << ch1 << " has occurred " <<
countOccurrences(str1, ch1) << " times in the given string." << endl;
string str2 = "peter piper picked a peck of pickled peppers";
char ch2 = 'p';
cout << "Input string 2: " << str2 << endl;
cout << "Character " << ch2 << " has occurred " <<
countOccurrences(str2, ch2) << " times in the given string." << endl;
string str3 = "I saw Susie sitting in a shoeshine shop";
char ch3 = 'a';
cout << "Input string 3: " << str3 << endl;
cout << "Character " << ch3 << " has occurred " <<
countOccurrences(str3, ch3) << " times in the given string." << endl;
string str4 = "Near an ear, a nearer ear, a nearly eerie ear";
char ch4 = 'r';
cout << "Input string 4: " << str4 << endl;
cout << "Character " << ch4 << " has occurred " <<
countOccurrences(str4, ch4) << " times in the given string." << endl;
string str5 = "He threw three free throws";
char ch5 = 'e';
cout << "Input string 5: " << str5 << endl;
cout << "Character " << ch5 << " has occurred " <<
countOccurrences(str5, ch5) << " times in the given string." << endl;
return 0;
}

Production:

 Input string 1: she sells seashells by the seashore
Character s has occurred 8 times in the given string.
Input string 2: peter piper picked a peck of pickled peppers
Character p has occurred 9 times in the given string.
Input string 3: I saw Susie sitting in a shoeshine shop
Character a has occurred 2 times in the given string.
Input string 4: Near an ear, a nearer ear, a nearly eerie ear
Character r has occurred 8 times in the given string.
Input string 5: He threw three free throws
Character e has occurred 6 times in the given string.

Programme Python pour compter le nombre total d'occurrences d'un caractère dans une chaîne

Vous trouverez ci-dessous le programme Python pour compter le nombre total d'occurrences d'un caractère dans une chaîne :

En relation: Comment valider des chaînes à l'aide de méthodes booléennes en Python

 # Python program to count occurrences
# of a given character in a string
# Function to count the occurrences of
# the given character in the string
def countOccurrences(str, ch):
# Counter variable
counter = 0
for char in str:
# check if the given character matches
# with the character in the string
if char == ch:
# if the given character matches with
# the character in the string,
# increment the counter variable
counter += 1
return counter
# Driver code
str1 = "she sells seashells by the seashore"
ch1 = 's'
print("Input string 1:", str1)
print("Character", ch1, "has occured",
countOccurrences(str1, ch1),"times in the given string.")
str2 = "peter piper picked a peck of pickled peppers"
ch2 = 'p'
print("Input string 2:", str2)
print("Character", ch2, "has occured",
countOccurrences(str2, ch2),"times in the given string.")
str3 = "I saw Susie sitting in a shoeshine shop"
ch3 = 'a'
print("Input string 3:", str3)
print("Character", ch3, "has occured",
countOccurrences(str3, ch3),"times in the given string.")
str4 = "Near an ear, a nearer ear, a nearly eerie ear"
ch4 = 'r'
print("Input string 4:", str4)
print("Character", ch4, "has occured",
countOccurrences(str4, ch4),"times in the given string.")
str5 = "He threw three free throws"
ch5 = 'e'
print("Input string 5:", str5)
print("Character", ch5, "has occured",
countOccurrences(str5, ch5),"times in the given string.")

Production:

 Input string 1: she sells seashells by the seashore
Character s has occurred 8 times in the given string.
Input string 2: peter piper picked a peck of pickled peppers
Character p has occurred 9 times in the given string.
Input string 3: I saw Susie sitting in a shoeshine shop
Character a has occurred 2 times in the given string.
Input string 4: Near an ear, a nearer ear, a nearly eerie ear
Character r has occurred 8 times in the given string.
Input string 5: He threw three free throws
Character e has occurred 6 times in the given string.

Programme JavaScript pour compter le nombre total d'occurrences d'un caractère dans une chaîne

Vous trouverez ci-dessous le programme JavaScript pour compter le nombre total d'occurrences d'un caractère dans une chaîne :

 // JavaScript program to count occurrences
// of a given character in a string
// Function to count the occurrences of
// the given character in the string
function countOccurrences(str, ch)
{
// Counter variable
var counter = 0;
for (let i = 0; i < str.length; i++)
{
// check if the given character matches
// with the character in the string
if (str[i] == ch)
{
// if the given character matches with
// the character in the string,
// increment the counter variable
counter++;
}
}
return counter;
}
// Driver code
var str1 = "she sells seashells by the seashore";
var ch1 = 's';
document.write("Input string 1: " + str1 + "<br>");
document.write("Character " + ch1 + " has occurred " +
countOccurrences(str1, ch1) + " times in the given string." + "<br>");
var str2 = "peter piper picked a peck of pickled peppers";
var ch2 = 'p';
document.write("Input string 2: " + str2 + "<br>");
document.write("Character " + ch2 + " has occurred " +
countOccurrences(str2, ch2) + " times in the given string." + "<br>");
var str3 = "I saw Susie sitting in a shoeshine shop";
var ch3 = 'a';
document.write("Input string 3: " + str3 + "<br>");
document.write("Character " + ch3 + " has occurred " +
countOccurrences(str3, ch3) + " times in the given string." + "<br>");
var str4 = "Near an ear, a nearer ear, a nearly eerie ear";
var ch4 = 'r';
document.write("Input string 4: " + str4 + "<br>");
document.write("Character " + ch4 + " has occurred " +
countOccurrences(str4, ch4) + " times in the given string." + "<br>");
var str5 = "He threw three free throws";
var ch5 = 'e';
document.write("Input string 5: " + str5 + "<br>");
document.write("Character " + ch5 + " has occurred " +
countOccurrences(str5, ch5) + " times in the given string." + "<br>");

Production:

 Input string 1: she sells seashells by the seashore
Character s has occurred 8 times in the given string.
Input string 2: peter piper picked a peck of pickled peppers
Character p has occurred 9 times in the given string.
Input string 3: I saw Susie sitting in a shoeshine shop
Character a has occurred 2 times in the given string.
Input string 4: Near an ear, a nearer ear, a nearly eerie ear
Character r has occurred 8 times in the given string.
Input string 5: He threw three free throws
Character e has occurred 6 times in the given string.

Connexes : Comment vérifier si une chaîne est un palindrome

Autres méthodes pour résoudre le problème

Vous pouvez trouver le nombre total d'occurrences d'un caractère dans une chaîne par d'autres méthodes telles que la récursivité, les expressions régulières, les fonctions de bibliothèque, etc. La méthode itérative utilisée dans cet article est l'une des méthodes les plus simples pour résoudre ce problème.

Si vous voulez pratiquer plus de problèmes sur les chaînes, découvrez des problèmes tels que comment inverser une chaîne, comment vérifier si une chaîne est un palindrome, comment trouver le nombre total de voyelles, de consonnes, de chiffres et de caractères spéciaux dans une chaîne, etc.