Removing whitespaces inside a string
Question
I have a string lots\t of\nwhitespace\r\n
which I have simplified but I still need to get rid of the other spaces in the string.
QString str = " lots\t of\nwhitespace\r\n ";
str = str.simplified();
I can do this erase_all(str, " ");
in boost but I want to remain in qt.
Solution
str = str.simplified();
str.replace( " ", "" );
The first changes all of your whitespace characters to a single instance of ASCII 32, the second removes that.
OTHER TIPS
Try this:
str.replace(" ","");
Option 1:
Simplify the white space, then remove it
Per the docs
[
QString::simplified
] Returns a string that has whitespace removed from the start and the end, and that has each sequence of internal whitespace replaced with a single space.
Once the string is simplified, the white spaces can easily be removed.
str.simplified().remove(' ')
Option 2:
Use a QRegExp
to capture all types of white space in remove
.
QRegExp space("\\s");
str.remove(space);
Notes
The OPs string has white space of different types (tab, carriage return, new line), all of which need to be removed. This is the tricky part.
QString::remove
was introduced in Qt 5.6; prior to 5.6 removal can be achieved usingQString::replace
and replacing the white space with an empty string""
.
You can omit the call to simplified()
with a regex:
str.replace(QRegularExpression("\\s+"), QString());
I don't have measured which method is faster. I guess this regex would perform worse.