查找
直接上代码
#include <QtWidgets/QApplication>
#include <Qstring>
#include <Qdebug>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QString str = "xcjasd,asdasd,{,[name],[id]},[name],asda[name]sd}sa";
qDebug() << str;
//取括号之前
int bpos = str.indexOf("{");//从前面开始查找
int epos = str.lastIndexOf("}");//从后面开始查找
qDebug() << str.left(bpos)<<bpos;//输出左边第N个字符串
//取括号后面
qDebug() << str.right(str.size()-epos-1);//输出右边第N个字符串
//取括号中间的的
QString str2 = str;//chop是直接对对象进行操作(会改变对象)
str2.chop(str2.size()-str2.lastIndexOf("}"));//chop把字符串后N个丢弃
qDebug() << str2;
qDebug() << str2.right(str2.size()-str2.indexOf("{")-1);
return a.exec();
}
结果
"xcjasd,asdasd,{,[name],[id]},[name],asda[name]sd}sa"
"xcjasd,asdasd," 14
"sa"
"xcjasd,asdasd,{,[name],[id]},[name],asda[name]sd"
",[name],[id]},[name],asda[name]sd"
以上对字符串处理函数进行了简单的使用以对“{ }”的前面、中间、后面的内容进行打印输出。
替换replace
#include <QtWidgets/QApplication>
#include <Qstring>
#include <Qdebug>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QString str = "xcjasd,asdasd,{,[name],[id]},[name],asda[name]sd}sa";
QString str2 = str;
qDebug() << str2;
str2.replace("[name]","xiaoming");
str2.replace("[id]", "007");
qDebug() << str2;
return a.exec();
}
结果
"xcjasd,asdasd,{,[name],[id]},[name],asda[name]sd}sa"
"xcjasd,asdasd,{,xiaoming,007},xiaoming,asdaxiaomingsd}sa"
以上可以看出替换操作也是直接对对象进行操作
字符串切割
#include <QtWidgets/QApplication>
#include <Qstring>
#include <Qdebug>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QString str = "xcjasd,asdasd,{,[name],[id]},[name],asda[name]sd}sa";
QStringList list1 = str.split(",");
for (int i = 0; i < list1.size(); i++)
{
qDebug() << list1[i];
}
return a.exec();
}
结果
"xcjasd"
"asdasd"
"{"
"[name]"
"[id]}"
"[name]"
"asda[name]sd}sa"
还可以通过正则表达式进行以上操作