0

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;
   

}
vakru
  • 25
  • 2
  • I would like to count the words starting with charr. – vakru May 31 '22 at 18:31
  • Do you get any errors from using `main` as a function and `main` as a variable? I recommend using less confusing names, like "main_string" and "user_char". – Thomas Matthews May 31 '22 at 19:49
  • I recommend using a constant temporary variable to hold the result of `main.size()`. No need to recalculate the size of the `main` string in each iteration. – Thomas Matthews May 31 '22 at 19:51

3 Answers3

2

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';
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
2

In your example, you fail to ensure the character before the one being checked is whitespace. Doing that and your approach will work. You don't want to know how many characters there are that match charr, you want to know how many words start with charr. To calculate that from the entire std::string, you need to check that the previous character is whitespace.

You can easily check whether the previous character is whitespace by including cctype and using the isspace() macro.

Additionally, you must validate EVERY user-input. The user may generate a manual EOF to cancel input which is a valid user-action. (Ctrl + d or Ctrl + z on windows).

A short example using your read with getline(), removing using namespace std; and choosing a new name for your string (line instead of main) would be:

#include <iostream>
#include <string>
#include <cctype>

int main()
{
    std::string line {};
    char charr = 0;
    int count = 0, last = 0;

    std::cout << "Enter the main string : ";
    /* validate read and line not empty */
    if (!getline(std::cin, line) || line.size() == 0) {
        return 0;
    }
    std::cout << "Enter a character: ";
    if (!(std::cin >> charr)) {                     /* validate read */
        return 0;
    }
    
    if (line[0] == charr) {                         /* check 1st char */
        count++;                                    /* increment on match */
    }
    last = line[0];                                 /* set last char seen */
    
    for (size_t i = 1; i < line.size(); i++) {      /* loop 1 to end */
        /* last is space and current is charr */
        if (isspace(last) && line[i] == charr) {
            count++;                                /* increment count */
        }
        last = line[i];                             /* set last char seen */
    }
    std::cout << count << '\n';                     /* output results */
}

(note: while using namespace std; may be fine and convenient for small example programs, see: Why is “using namespace std;” considered bad practice?)

Example Use/Output

$ ./bin/startswith
Enter the main string : my dog has fleas and my cat has none
Enter a character: h
2

Or

$ ./bin/startswith
Enter the main string : my dog has fleas and my cat has none
Enter a character: n
1
David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
0
std::stringstream ss;
ss << main;
string word;
while(ss >> word)
{
  if(word[0] == charr)
    ++count;
}

EDIT: correction using comment of Ted Lyngmo. Thanks.

melmi
  • 988
  • 3
  • 9
  • 27