Grupo
Control de Flujo en C++
Ojetivo
1. Solicitar al usuario que introduzca una cadena.
2. Solicitar al usuario el carácter que desea buscar.
3. Usar un bucle para iterar la cadena y contar las veces que aparece el carácter.
4. Mostrar el resultado al usuario.
Escribir un programa que cuente las veces que aparece un carácter en una cadena.
Ejemplo de Código C++
Mostrar Código C++
#include <iostream> // Include the iostream library for input and output
#include <string> // Include the string library to work with string data types
using namespace std; // Use the standard namespace
// Main function - entry point of the program
int main() {
string str; // Variable to store the input string
char ch; // Variable to store the character to search for
int count = 0; // Variable to count the occurrences of the character
// Prompt the user to enter a string
cout << "Enter a string: ";
getline(cin, str); // Read the entire line of input into the string
// Ask the user to input the character to search for
cout << "Enter a character to search for: ";
cin >> ch; // Read the character input
// Loop through the string to count occurrences of the character
for (int i = 0; i < str.length(); i++) { // Iterate through each character in the string
if (str[i] == ch) { // If the current character matches the one being searched
count++; // Increment the count
}
}
// Output the result to the user
cout << "The character '" << ch << "' appears " << count << " times in the string." << endl;
return 0; // Return 0 to indicate successful execution of the program
}
Salida
Enter a string: Hello World
Enter a character to search for: o
The character 'o' appears 2 times in the string.
//Or for another string:
Enter a string: OpenAI is great
Enter a character to search for: i
The character 'i' appears 2 times in the string.
Comparte este ejercicio C++