Contare le occorrenze di un carattere in String C++

Jinku Hu 12 ottobre 2023
  1. Utilizzare il metodo iterativo per contare le occorrenze di un carattere in una stringa
  2. Usa la funzione std::tolower per contare le occorrenze di caratteri indipendentemente dalle maiuscole e dalle minuscole
Contare le occorrenze di un carattere in String C++

Questo articolo spiegherà diversi metodi su come contare le occorrenze di un carattere in una stringa C++.

Utilizzare il metodo iterativo per contare le occorrenze di un carattere in una stringa

La libreria di stringhe C++ fornisce una classe std::string, che può essere usata per memorizzare e manipolare sequenze di oggetti simili a char. Fornisce più metodi per cercare e trovare il carattere specificato o una sottostringa nella stringa, ma in questo caso, dobbiamo controllare ogni carattere in modo che sia più semplice implementare una funzione che itera attraverso la stringa mentre si incrementa la variabile count . Questa funzione accetta un oggetto string come riferimento e un carattere come valore per contare le occorrenze. Attenzione però, questa versione non distingue le lettere maiuscole da quelle minuscole, quindi non può essere utilizzata quando il conteggio deve includere caratteri sia maiuscoli che minuscoli.

#include <iostream>
#include <string>
#include <vector>

using std::cerr;
using std::cout;
using std::endl;
using std::string;

size_t countOccurrences(char c, string &str) {
  size_t count = 0;

  for (char i : str)
    if (i == c) count++;

  return count;
}

int main() {
  char ch1 = 'e';
  char ch2 = 'h';
  string str1("hello there, how are you doing?");
  string str2("Hello there! How are you doing?");

  cout << "number of char - '" << ch1
       << "' occurrences = " << countOccurrences(ch1, str1) << endl;
  cout << "number of char - '" << ch2
       << "' occurrences = " << countOccurrences(ch2, str2) << endl;

  exit(EXIT_SUCCESS);
}

Produzione:

number of char - 'e' occurrences = 4
number of char - 'h' occurrences = 1

Usa la funzione std::tolower per contare le occorrenze di caratteri indipendentemente dalle maiuscole e dalle minuscole

Un altro metodo per implementare l’esempio precedente è riscrivere la funzione countOccurrences per confrontare i valori convertiti dei caratteri ad ogni iterazione. Nota che std::tolower è difficile da usare in quanto richiede che l’unico argomento char sia rappresentabile come unsigned char; in caso contrario, il comportamento è indefinito. Quindi, passiamo il valore cast unsigned char alla funzione tolower e poi lo restituiamo a char per memorizzarlo in una variabile temporanea - tmp. Inoltre, chiamiamo la funzione tolower ogni iterazione per convertire i caratteri della stringa in lettere minuscole per l’istruzione di confronto. Si noti che il seguente codice di esempio può distinguere i caratteri in maiuscolo e minuscolo e contarli tutti.

#include <iostream>
#include <string>
#include <vector>

using std::cerr;
using std::cout;
using std::endl;
using std::string;

size_t countOccurrences(char c, string &str) {
  size_t count = 0;
  char tmp = static_cast<char>(tolower(static_cast<unsigned char>(c)));

  for (char i : str)
    if (tolower(static_cast<unsigned char>(i)) == tmp) count++;

  return count;
}

int main() {
  char ch1 = 'e';
  char ch2 = 'h';
  string str1("hello there, how are you doing?");
  string str2("Hello there! How are you doing?");

  cout << "number of char - '" << ch1
       << "' occurrences = " << countOccurrences(ch1, str1) << endl;
  cout << "number of char - '" << ch2
       << "' occurrences = " << countOccurrences(ch2, str2) << endl;

  exit(EXIT_SUCCESS);
}

Produzione:

number of char - 'e' occurrences = 4
number of char - 'h' occurrences = 3
Autore: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn Facebook

Articolo correlato - C++ Char