226k views
4 votes
Write a program whose input is a character and a string, and whose output indicates the number of times the character appears in the string. You may assume that the string does not contain spaces and will always contain less than 50 characters.Ex: If the input is:n Mondaythe output is:1Ex: If the input is:z TodayisMondaythe output is:0Ex: If the input is:n It'ssunnytodaythe output is:2Case matters.Ex: If the input is:n Nobodythe output is:0n is different than N.C++ Code:#include #include int main(void) {/* Type your code here. */return 0;}

User Hbaltz
by
4.8k points

2 Answers

7 votes

Final answer:

To count the number of times a character appears in a string in C++, you can iterate through each character and compare it to the given character. If there is a match, increment a counter variable. Finally, output the count.

Step-by-step explanation:

To count the number of times a character appears in a string using C++, you can iterate through each character in the string and compare it to the given character. If there is a match, you increment a counter variable. Here's an example of how you can implement this:

#include <iostream>
#include <string>

int main() {
char character;
std::string input;
int count = 0;

std::cout << "Enter a character: ";
std::cin >> character;

std::cout << "Enter a string: ";
std::cin.ignore();
std::getline(std::cin, input);

for (char c : input) {
if (c == character) {
count++;
}
}

std::cout << "The character " << character << " appears " << count << " times in the string." << std::endl;

return 0;
}

In this code, we use a for-each loop to iterate through each character of the input string. If the character matches the given character, we increment the count variable. Finally, we output the number of times the character appears in the string.

User Anthony Geoghegan
by
5.1k points
2 votes

Final answer:

To count the occurrences of a character within a string in C++, you can iterate through the string, comparing each character with the input character and incrementing a counter whenever they match. The program then outputs the count.

Step-by-step explanation:

The program you're looking to write in C++ will count the occurrences of a given character within a string. Here's how you can implement this:

#include <iostream>
#include <string>
using namespace std;
int main() {
char searchChar;
string inputString;
int count = 0;
// Read character and string
cin >> searchChar;
cin >> inputString;
// Count occurrences of searchChar in inputString
for (int i = 0; i < inputString.length(); ++i) {
if (inputString[i] == searchChar) {
count++;
}
}
// Output the count
cout << count << endl;
return 0;
}

Remember that each time a character in the string matches the character you're looking for, you add to the count, and this final count is what the program outputs. Make sure you test your program with various inputs to ensure case sensitivity and correct functioning.

User Eric Niebler
by
4.6k points