C++ 如何从qt中的字符串中获取子字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23033112/
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
How to get substring from a string in qt?
提问by amol01
I have a text form:
我有一个文本表单:
Last Name:SomeName, Day:23 ...etc
From Last Name:SomeName, I would like to get Last Name, and separately SomeName.
从姓氏:SomeName,我想获得姓氏,并分别获得 SomeName。
I have tried to use QRegularExpression,
我曾尝试使用 QRegularExpression,
QRegularExpression re("(?<label>\w+):(?<text>\w+)");
But I am getting the result:
但我得到了结果:
QString label = match.captured("label") //it gives me only Name
What I want is whatever text till ":" to be label, and after to be text.
我想要的是任何文本直到“:”成为标签,然后成为文本。
Any ideas?
有任何想法吗?
回答by lpapp
You could use two different methods for this, based on your need:
您可以根据需要使用两种不同的方法:
main.cpp
主程序
#include <QString>
#include <QDebug>
int main()
{
QString myString = "Last Name:SomeName, Day:23";
QStringList myStringList = myString.split(',').first().split(':');
qDebug() << myStringList.first() << myStringList.last();
return 0;
}
main.pro
主程序
TEMPLATE = app
TARGET = main
QT = core
SOURCES += main.cpp
Build and Run
构建和运行
qmake && (n)make
Output
输出
"Last Name" "SomeName"