Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Remove all special characters in a string



  • Hi. I would like to remove all special characters from the string.

    This is my code.

                str = str.simplified();
                str = str.remove("!");
                str = str.remove("@");
                str = str.remove("#");
                str = str.remove("$");
                str = str.remove("%");
                str = str.remove("^");
                str = str.remove("&");
                str = str.remove("*");
                str = str.remove("(");
                str = str.remove(")");
                str = str.remove("_");
                str = str.remove("+");
                str = str.remove("-");
                str = str.remove("=");
                str = str.remove(";");
                str = str.remove("'");
                str = str.remove(":");
                str = str.remove('"');
                str = str.remove("'");
                str = str.remove("/");
                str = str.remove(".");
                str = str.remove(",");
                str = str.remove("<");
                str = str.remove(">");
                str = str.remove("?");
                str = str.remove("[");
                str = str.remove("]");
                str = str.remove("{");
                str = str.remove("}");
                str = str.remove(" ");
    

    Of course it works well, but ... Is there more productive code?

    Thanks in advance for your advice.


  • Lifetime Qt Champion


  • Moderators

    Or, if you don't feel like bothering with regular expressions:

    auto it = std::remove_if(str.begin(), str.end(), [](const QChar& c){ return !c.isLetterOrNumber();});
    str.chop(std::distance(it, str.end()));
    

Log in to reply