Search code examples
c++stringsubstringstringstream

How to remove all the words from a string that start with a certain character in C++


I have to create a function in C++ that would remove all the words from a string that start with a certain character inputted by a user. For example, if I were to have a string "She made up her mind to meet up with him in the morning" and a substring "m", I would get a result string "She up her to up with him in the". I believe I would need to find the occurrences of "m", erase it and all the characters after it till the space " ". Would that be the right approach and if so what would be the best methods to use in this case?


Solution

  • What I needed to read about was how stringstream and >> work. Thanks everyone for the help! Here is the code.

    void deleteWordsStartingWithChar(string& str, char c) {
        istringstream ss(str);
        ostringstream oss;
        std::string word;    
        while (ss >> word) {
            if (word[0] == c) {
                continue;
            }
            oss << word << " ";
        }
    
        str = oss.str();
    }