如何从Qstring获得第一个单词

mkr*_*ddy 1 qstring qt qregexp

我想得到第一个字Qstring.

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

如果我遇到我的第一个空格string1,我需要的那部分string1string2.

Rud*_*rde 6

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

QString firstWord = string1.split(" ").at(0);
Run Code Online (Sandbox Code Playgroud)

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

  • 在文档中,它表示如果没有出现,split()将返回包含字符串本身的单元素列表.所以它总会返回至少一个元素列表. (3认同)

Ale*_*x P 5

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

例如,最基本的语法是:

QString str = "Do re mi";
QString firstWord = str.section(" ", 0, 0);
// firstWord = "Do"
Run Code Online (Sandbox Code Playgroud)

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

QString str = "\tDo    re\nmi"; // tabs and newlines and spaces, oh my!
QString firstWord = str.section(QRegExp("\\s+"), 0, 0, 
    QString::SectionSkipEmpty);
// firstWord = "Do"
Run Code Online (Sandbox Code Playgroud)