char*,QString,String类型的相互转换

Qt下常用的字符处理的转换方法:

(1) char*——string

char* to string

const char* str1 = "this is a const char*";
string str2(str1);

string to char*

string str1 = "this is a string";
char* str2 = const_cast(str1.c_str());

(2) char*——QString

char* to QString

const char* test = "this is a string";
QString ts(QString::fromLocal8Bit(test));//first way
ts = QString(QLatin1String(test));//second way

QString to char*

QString str1 = "this is a qstring";
const char* str2 = str1.tolocal8bit();

(3) QString——String

#include   
#include   
#include   
#include 
  
using namespace std;  
QString s2q(const string &s);  
string q2s(const QString &s); 

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






你可能感兴趣的:(Qt+Linux开发)