QString split 跳过换行和空格’
时间: 2023-11-24 20:05:49 浏览: 96
在Qt中,QString的split函数可以使用正则表达式作为分隔符。因此,您可以使用正则表达式来跳过换行和空格。
以下是一个示例代码,它使用正则表达式\s+作为分隔符,该表达式匹配一个或多个空格或制表符:
```
QString str = "hello world\nhow are you";
QStringList list = str.split(QRegExp("\\s+"));
foreach(QString s, list) {
qDebug() << s;
}
```
输出将是:
```
"hello"
"world"
"how"
"are"
"you"
```
在这个例子中,我们使用了QRegExp类来创建正则表达式,然后将其作为参数传递给split函数。注意,反斜杠需要被转义。
如果您只想跳过换行符,可以使用正则表达式\n作为分隔符。如果您只想跳过空格,可以使用正则表达式\s作为分隔符。
相关问题
QString split 跳过换行和空格且按照需要的划分方式划分
可以使用正则表达式来实现按照需要的划分方式划分,并使用QStringList存储结果。
例如,假设需要按照“,”、“。”、“!”、“?”作为分隔符划分字符串,可以使用以下代码:
```cpp
QString str = "Hello, world. How are you today! I am fine, thank you?";
QStringList list = str.split(QRegExp("[,\\.!?\\s]+"), QString::SkipEmptyParts);
```
其中,QRegExp("[,\\.!?\\s]+")表示使用“,”、“。”、“!”、“?”和空格作为分隔符,QString::SkipEmptyParts表示跳过空的分隔符结果。最终结果存储在QStringList list中。
qt QString split
The QString split function is used to split a QString object into a list of substrings based on a separator. The syntax for the QString split function is as follows:
QStringList QString::split(const QString &separator, Qt::SplitBehavior behavior = Qt::KeepEmptyParts) const
The separator parameter specifies the character or string that is used to split the QString object into substrings. The behavior parameter specifies how the function should handle empty strings that may be generated by splitting the QString object.
The QString split function returns a QStringList object that contains the substrings generated by splitting the QString object. The substrings are stored in the list in the order in which they appear in the original QString object.
Here is an example of how the QString split function can be used to split a QString object into substrings:
QString str = "Hello, World!";
QStringList list = str.split(", ");
// The resulting list contains "Hello" and "World!" as separate strings.