3

我想得到 a 的第一个单词Qstring

例如String1 = "Read from file1". 我想提取string2 = "Read". 我想根据空格提取子字符串。

如果我在我的 中遇到第一个空格,我需要tostring1的那一部分。string1string2

4

3 回答 3

6

QString以这种方式使用 split 函数:

QString firstWord = string1.split(" ").at(0);

如果字符串中没有空格,则返回整个字符串。

于 2014-02-06T13:52:51.670 回答
5

QString::split如果您想使用所有部分,或者只想QString::section抓住第一个单词,请使用。

例如,最基本的语法是:

QString str = "Do re mi";
QString firstWord = str.section(" ", 0, 0);
// firstWord = "Do"

如果您需要处理各种奇怪的空格,可以使用函数的正则表达式版本

QString str = "\tDo    re\nmi"; // tabs and newlines and spaces, oh my!
QString firstWord = str.section(QRegExp("\\s+"), 0, 0, 
    QString::SectionSkipEmpty);
// firstWord = "Do"
于 2014-02-06T14:04:14.377 回答
1

我会做:

QString s("Read from file1");
QString subStr = s.section(" ", 0, 0, QString::SectionSkipEmpty);

在这种字符串的情况下,这也将正常工作:

“从文件 1 中读取”

于 2014-02-06T13:55:43.177 回答