Replace a specific word containing a space (string)

So, Ive written a chatfilter for this game I do some programming on. It's mostly working, but if the uses adds a space between the abusive word, it doesn't filter it. Was wondering if anyone knew the best way to fix that. I tried using remove_if, but it crashed my program.

Example:

string strMsg = szMsg; //copy contents of szMsg to strMsg (easier to manipulate). szMsg is defined in the function prototype as a char ptr
if (!CheckChatFilter(strMsg.c_str())) //strMsg utilized from here down
{
if (m_nLastAbuseTime < 1 && StrStrI(strMsg.c_str(), MGetChattingFilter()->GetLastFilteredStr().c_str())) //ignore case
{
strMsg.replace(remove_if(MGetChattingFilter()->GetLastFilteredStr().begin(), MGetChattingFilter()->GetLastFilteredStr().end(), ::isspace),MGetChattingFilter()->GetLastFilteredStr().end()); // Crash caused by this
string::size_type pos = strMsg.find(MGetChattingFilter()->GetLastFilteredStr());
if (pos != string::npos)
{
strMsg.replace(pos, MGetChattingFilter()->GetLastFilteredStr().size(), "*beep*");
}

}
else
{
return false;
}
}
Last edited on
Consider using regular expressions for this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <string>
#include <regex>

int main()
{
    const std::string message = "message containing an Abusive Word with a space in it,\n"
                                "a non-abusive word, and another Abusive    Word with many spaces in it" ;
    const std::string replace_with = "*****" ;

    {
        const std::string remove_this = "abusive word" ; // containing exactly one space

        // http://en.cppreference.com/w/cpp/regex/basic_regex/basic_regex
        // std::regex_constants::icase ignore case
        std::regex abusive_re( remove_this, std::regex_constants::ECMAScript | std::regex_constants::icase ) ;

        // http://en.cppreference.com/w/cpp/regex/regex_replace
        const std::string sanitised_message = std::regex_replace( message, abusive_re, replace_with ) ;
        std::cout << sanitised_message << "\n\n" ;
    }

    {
        // starting with a space (\s), and containing one or more spaces (\s+)
        const std::string remove_this = "\\sabusive\\s+word" ;
        std::regex abusive_re( remove_this, std::regex_constants::ECMAScript | std::regex_constants::icase ) ;
        const std::string sanitised_message = std::regex_replace( message, abusive_re, ' ' + replace_with ) ;
        std::cout << sanitised_message << '\n' ;
    }
}

http://coliru.stacked-crooked.com/a/6767d4d114d306c0
Topic archived. No new replies allowed.