Remove all special characters in a string
Solved
General and Desktop
-
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.
-
@Kycho use a regular expression and http://doc.qt.io/qt-5/qstring.html#replace-12
-
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()));