28

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.

Durandal
  • 5,575
  • 5
  • 35
  • 49
Gandalf
  • 1
  • 29
  • 94
  • 165

4 Answers4

64
str = str.simplified();
str.replace( " ", "" );

The first changes all of your whitespace characters to a single instance of ASCII 32, the second removes that.

arnt
  • 8,949
  • 5
  • 24
  • 32
  • @noone in that case you should probably make a simple test case and report a bug, because according to the documentation it still ought to. – arnt Aug 29 '18 at 11:16
  • sorry. My bad . I had not included QString –  Aug 29 '18 at 12:26
13

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 using QString::replace and replacing the white space with an empty string "".

Terrabits
  • 997
  • 2
  • 15
  • 19
13

Try this:

str.replace(" ","");
tonekk
  • 470
  • 3
  • 16
0

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.

Martin Hennings
  • 16,418
  • 9
  • 48
  • 68