【QT】QString字符串分割--通过字符分割或字符串分割

一、通过字符串位置索引截取

namespace N_D_Com_Modbus
{
	const QString TCP_HEAD = "TCP_HEAD";//Tcp字节头
	const QString TCP_END = "TCP_END";//Tcp字节尾
	const QString RLT_RES = "RLT_RES";
};
//QString s1[50];
//QString stemp = "TCP_HEADRLT_REQ@16127@TCP_ENDTCP_HEADRLT_REQ@16126@TCP_ENDTCP_HEADSTA_ID@21,16145#22,16144TCP_ENDTCP_HEADSTA_ID@31,16141#32,16140TCP_ENDTCP_HEADSTA_ID@41,16137#42,16136TCP_ENDTCP_HEADSTA_ID@51,16133#52,16132TCP_ENDR#1000@R#0@TCP_HEADRLT_REQ@16129@TCP_ENDTCP_HEADRLT_REQ@16128@TCP_END";
	QStringList recvTpList;
	QString strTp = stemp ;
	for (int i = 0; i < 50; i++)
	{
		bool b = strTp.contains("TCP_END", Qt::CaseSensitive);
		if (!b)
			break;
		int n = strTp.indexOf("TCP_END");
		QString tepStr= strTp.mid(0, n + 7);
		recvTpList << tepStr;
		qDebug() << "拆分TCP_END后:" << tepStr;
		strTp = strTp.mid(n + 7);
	}
	/*
	TCP_HEADRLT_REQ@16127@TCP_END
	TCP_HEADRLT_REQ@16126@TCP_END
	TCP_HEADSTA_ID@21,16145#22,16144TCP_END
	TCP_HEADSTA_ID@31,16141#32,16140TCP_END
	TCP_HEADSTA_ID@41,16137#42,16136TCP_END
	TCP_HEADSTA_ID@51,16133#52,16132TCP_END
	R#1000@R#0@TCP_HEADRLT_REQ@16129@TCP_END
	TCP_HEADRLT_REQ@16128@TCP_END
	*/

二、通过替换字符截取

QStringList recvList;
if (str.contains("TCP_ENDTCP_HEADSTA_ID@")&& str.contains("TCP_ENDTCP_HEADRLT_REQ@"))
{
	QString strTp=str;
	strTp.replace("TCP_END", "/t");
	recvList=strTp.split("/t");
}
/*
TCP_HEADRLT_REQ@16127@
TCP_HEADRLT_REQ@16126@
TCP_HEADSTA_ID@21,16145#22,16144
TCP_HEADSTA_ID@31,16141#32,16140
TCP_HEADSTA_ID@41,16137#42,16136
TCP_HEADSTA_ID@51,16133#52,16132
R#1000@R#0@TCP_HEADRLT_REQ@16129@
TCP_HEADRLT_REQ@16128@
*/

你可能感兴趣的:(QT,qt,网络,tcp/ip)