前言:
1、本文操作均为在vs2015+QT5.9.5版本中执行
2、本文操作是基于Qt窗口进行使用
main.cpp
#include <QtCore/QCoreApplication>
#include <iostream>
#include <QDebug>
using namespace std;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
//字符串读取
QString str = "xcjasd,asdasd{sa,[name],[id]},[name]},asda[name]}ssdsa";
for (int i = 0; i < str.size(); i++)
{
//由于QCharRef类型无法读取,需要转换成ASCII码进行读取。
cout << str[i].toLatin1();//“toLatin1()拉丁文”也就是ASCII编码方式
}
cout << endl;
cout << "=================================================================" << endl;
//遍历器读取字符串
QString::iterator itr;//一个QString的遍历器
for (itr = str.begin(); itr != str.end(); itr++)
{
//两种方式遍历转换,
//第一种:指针遍历访问toLatin1()转换
//cout << (*itr).toLatin1();
//第二种:遍历器指向toLatin1()转换
cout << itr->toLatin1();
}
cout << endl;
cout << "=================================================================" << endl;
//目标访问查找
QString key = "[name]";
//找到第一个name的位置
int pos = str.indexOf(key);
cout << "pos=" << pos << endl << endl;
//找到第二个name的位置
int pos2 = str.indexOf(key, pos + 1);//在这里可以使用+1进行查找
cout << "pos2=" << pos2 << endl << endl;
//找到第三个name的位置
int pos3 = str.indexOf(key, pos2 + key.size());//或者采用这个方法pos2 + key.size()
cout << "pos3=" << pos3 << endl << endl;
//如果没有这个值它会返回为 -1;
cout << str.indexOf("ttttt") << endl;
cout << "=================================================================" << endl;
//字符串截取
//str.chop(5);//去掉后面五位
//qDebug() <<QString::fromLocal8Bit("减去后五位=")<< str;
//获取位置字符位:
int b_pos =str.indexOf("{");//获取"{"位置 数值:13
int e_pos = str.lastIndexOf("}");//获取"}"的位置 数值:46
//left(b_pos);获取从左开始到b_pos之前数值的字符串 PS:不包括"{"本身
qDebug() << QString::fromLocal8Bit("取大括号之前=") << str.left(b_pos) << endl;
//right(e_pos);获取从右边到"}"数值的字符串
//PS:str.right(字符串长度 - e_pos - 减去一个"}"位置),不减去的话会包括"}"本身
qDebug() << QString::fromLocal8Bit("取大括号之后=") << str.right(str.size() - e_pos - 1) << endl;
//取中间的字符串
QString str2 = str;
str2.chop(str2.size() - e_pos);//减去从右边到"}"之前的字符串
qDebug() << QString::fromLocal8Bit("取大括号中间的字符串=") << str2.right(e_pos - b_pos-1) << endl;
cout << "=================================================================" << endl;
//字符串替换
QString str3 = str;
/********************************************/
//替换[name]为zzp
str3.replace("[name]","zzp");
//读取操作
cout << "[name]字符串替换后:";
for (int i = 0; i < str3.size(); i++)
{
cout<< str3[i].toLatin1();
}
cout << endl << endl;
/********************************************/
//替换[id]为15
str3.replace("[id]", "15");
qDebug() << QString::fromLocal8Bit("[id]字符串替换后:") << str3 <<endl;
/********************************************/
cout << "=================================================================" << endl;
//字符串切割
QString str4 = str;
//split();切割字符串函数,用法如下
QStringList str_list = str4.split(",");
//遍历操作
for (int i = 0; i < str_list.size(); i++)
{
qDebug() << QString::fromLocal8Bit("字符串切割后=")<< str_list[i];
}
cout << endl;
cout << "=================================================================" << endl;
return a.exec();
}