I've managed to get the count of the user entered character in any place of the string, but how would I get count of only the words that start with the user entered character?
#include <iostream>
#include <string>
using namespace std;
int main()
{
string main;
char charr;
cout << "Enter the main string : "<<endl;
getline(cin,main);
cout << "Enter a character: "<<endl;
cin >> charr;
int count = 0;
for (int i = 0; i < main.size(); i )
if (main[i] == charr)
count ;
cout << count << endl;
}
CodePudding user response:
You could put the std::string
in a std::istringstream
and then std::count_if
the words starting with the entered character.
It could look like this:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
int main() {
std::string main;
char charr;
std::cout << "Enter the main string:\n";
std::getline(std::cin, main);
std::cout << "Enter a character:\n";
if(not (std::cin >> charr)) return 1;
std::istringstream is(main); // put the main string in an istringstream
// count words starting with charr:
auto count = std::count_if(std::istream_iterator<std::string>(is),
std::istream_iterator<std::string>{},
[charr](const std::string& word) {
return word.front() == charr;
});
std::cout << count << '\n';
}
CodePudding user response:
std::stringstream ss;
ss << main;
string word;
while(ss >> word)
{
if(word[0] == charr)
count;
}
EDIT: correction using comment of Ted Lyngmo. Thanks.