Qt字符串转换和处理----山路十八弯

公司最近要求用Qt写程序,最郁闷的就是字符串之间的转化。搞的自己七荤八素的!还好本人耐折腾。。。自己也尝试出了几种Qt自带的转换方法。


#include <QtGui/QApplication>
#include "testqstring.h"
#include "boost/lexical_cast.hpp"
#include <iostream>
#include <string>
#include <stdio.h>
#include <QDebug>
using namespace std;

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    testQString w;
    w.show();

    QString qStr="testString";
    qDebug()<<"wyz-------1:"<<qStr;

    string str=qStr.toStdString();
    cout<<"wyz-------2:"<<str<<endl;

    char *cStr;
    cStr=(char*)str.c_str();
    cout<<"wyz-------3:"<<cStr<<endl;

    string str_1="testString2";
    QString qStr_1;
    qStr_1.sprintf("%s",str_1.c_str());
    qDebug()<<"wyz-------4:"<<qStr_1;


    return a.exec();
}

运行结果:

Starting /root/testQString-build-desktop/testQString...
wyz-------1: "testString" 
wyz-------2:testString
wyz-------3:testString
wyz-------4: "testString2" 

 

int 转 QString
QString & sprintf ( const char * cformat, ... )

string strData= write1.write(smsJson);
strData = boost::erase_all_copy(strData, "\n");

 

string strTemp= m_qStrInfo.toStdString();

vector<string > splitVec;
boost::split(splitVec, strTemp, boost::is_any_of("\r\n"));

 

 

 


========网上copy来copy去的资料=============

//常用参数类型:char *字符串, QByteArray字符数组, QString字符串
//需要转换:char * ---转--- QByteArray ---需要调用QByteArray类的构造函数
char*     --------------QByteArray(const char*)-----------> QByteArray
char* str;
QByteArray byte(str);


char*     --------------QString(const char*)-------------->QString
char* str;
QString string(str);


QByteArray   -------------data()-------------------->char*
QByteArray byte;
char* str = byte.data();


QByteArray ------------QString()------------------->QString
QByteArray byte;
QString string(byte);


QString --------------toAscii()--------------------> QByteArray
QString string;
QByteArray byte = string.toAscii();


QString -------------qPrintable()------------------>char*
QString string;
char* str = qPrintable(string);



QString s2q(const string &s)
{
    return QString(QString::fromLocal8Bit(s.c_str()));
}
string q2s(const QString &s)
{
    return string((const char *)s.toLocal8Bit());
}



QByteArray qba = m_pTcpSocket->readAll();
QString strings(qba);   //转换成qt字符串



QByteArray qba = tcpSocket->readAll();
char *readStr=qba.data();    //把QByteArray转换成char


你可能感兴趣的:(String,qt,byte)