mkr*_*ddy 1 qstring qt qregexp
我想得到第一个字Qstring.
例如String1 = "Read from file1".我想提取string2 = "Read".我想基于空格提取子字符串.
如果我遇到我的第一个空格string1,我需要的那部分string1来string2.
QString以这种方式使用split函数:
QString firstWord = string1.split(" ").at(0);
Run Code Online (Sandbox Code Playgroud)
如果字符串中没有空格,则返回整个字符串.
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)