Reputation: 41
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?
Upvotes: 0
Views: 484
Reputation: 316
Simple example in french. You are a classy gentleman and dont want to say "merde" too often. This is very hard, so you decided not to say any word starting with 'm'. This program will help you :
"merde je suis beau merde je le sais" becomes "je suis beau je le sais"
#include <string>
#include <algorithm>
#include <iostream>
int main () {
std::string str ("merde je suis beau merde je le sais");
const auto forbidden_start ('m');
std::cout << "initial rude string (words starting with \'" << forbidden_start << "\" : \"" << str << "\"" << std::endl;
auto i (str.begin ());
auto wait ((int) 0);
std::for_each (str.begin (), str.end (), [&i, &forbidden_start, &wait] (const auto& c) {
if (wait) {
if (c == ' ') --wait;
}
else {
if (c == forbidden_start) ++wait;
else *i++ = c;
}
});
if (i != str.end ()) str.erase (i, str.end ());
std::cout << "\tpolite string : \"" << str << "\"" << std::endl;
}
All is not tested (separator is " "), but it is the idea
Upvotes: 1
Reputation: 41
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();
}
Upvotes: 0
Reputation: 104589
Here's a hint. I'm guessing this is a homework problem. And I'm probably giving too much away.
std::string GetNextWord(const std::string &s, size_t pos)
{
std::string word;
// your code goes here to return a string that includes all the chars starting from s[pos] until the start of the next word (including trailing whitespace)
// return an empty string if at the end of the string
return word;
}
std::string StripWordsThatBeginWithLetter(const std::string& s, char c)
{
std::string result;
std::string word;
size_t pos = 0;
while (true)
{
word = GetNextWord(s, pos);
pos += word.size();
if (word.size() == 0)
{
break;
}
// your code on processing "word" goes here with respect
// to "c" goes here
}
return result;
}
Upvotes: 3