C++ 去除字符串中的空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8256190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:16:20  来源:igfitidea点击:

Removing whitespaces inside a string

c++qtqstring

提问by Gandalf

I have a string lots\t of\nwhitespace\r\nwhich I have simplified but I still need to get rid of the other spaces in the string.

我有一个lots\t of\nwhitespace\r\n已经简化的字符串 ,但我仍然需要去掉字符串中的其他空格。

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.

我可以erase_all(str, " ");在 boost 中做到这一点,但我想留在 qt 中。

回答by arnt

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

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

第一个将所有空白字符更改为 ASCII 32 的单个实例,第二个将其删除。

回答by tonekk

Try this:

尝试这个:

str.replace(" ","");

回答by Terrabits

Option 1:

选项 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.

[ QString::simplified] 返回一个字符串,该字符串从开头和结尾删除了空格,并将每个内部空格序列替换为一个空格。

Once the string is simplified, the white spaces can easily be removed.

一旦字符串被简化,就可以轻松删除空格。

str.simplified().remove(' ')

Option 2:

选项 2

Use a QRegExpto capture all types of white space in remove.

使用 aQRegExp来捕获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::removewas introduced in Qt 5.6; prior to 5.6 removal can be achieved using QString::replaceand replacing the white space with an empty string "".

  • OPs 字符串有不同类型的空格(制表符、回车符、换行符),所有这些都需要删除。这是棘手的部分。

  • QString::remove在 Qt 5.6 中引入;在 5.6 之前,可以使用QString::replace空字符串替换空格来实现删除""

回答by Martin Hennings

You can omit the call to simplified()with a regex:

您可以simplified()使用正则表达式省略调用:

str.replace(QRegularExpression("\s+"), QString());

I don't have measured which method is faster. I guess this regex would perform worse.

我没有测量哪种方法更快。我猜这个正则表达式会表现得更糟。