好多人都喜欢重新造一个轮子, 所以这个世界上的的轮子千奇百怪. 作为在这些轮子下面苟延残喘的洒家,往往不得不无尽的寻找两个轮子之间转换的方法. STL库, 作为标准库, 在写C++的时候理所当然的, 被各种使用. const char * 数组, 作为和C一起过来的小伙伴, 在很多场合下也会被调用. 如果脑抽居然还打算使用Qt, 那么,Qt自带的QString, 恐怕也很难有人能完全不使用. 于是乎, 类型转换就是个问题了.

const char * 数组和 STL的转换, 这两者的转换最为常见.

const char * => STL 我一般直接使用

const char * s = "hello , world!";
string str(s);

直接赋值完毕了.

如果是作为一个参数,还可以直接用调用string的构造函数.

const char * s = "hello const char";
string s1("hello , string1 ");
string s2 = s1 + string(s);

s2就这样轻松搞定.

需要注意的是, string 的拼接不建议用上述的写法, 若条件允许, 写成这样会更好一些:

const char * s = "hello const char";
string s1("hello , string1 ");
s1 += string(s);

string 到const char *就更加简单了

string str("hello world !");
const char * s = str.c_str();

不过需要注意的是,这个当前stack下只能被调用一次,就会被系统自动释放掉. 当然,你可以作为参数传入某个function,然后被调用很多遍,然后一return这个s就不能再用了. 所以这个 .c_str() 似乎专门就是为了传参时候的类型转换用的.

QString这个第三者的加入 const char * => QString, QString当然不敢不支持. 和STL的string一样,

const char * s = "hello , world !";
QString qs1(s);
QString qs2 = qs1.append(QString(s));

两种方法都是可以的.

如果需要特定编码的话,还可以

QString qs3= QString(QLatin1String(s));
QString qs4 = QString::fromLocal8Bit(s);

而QString=> *有很多方法.最直白的是这样的

QString qs1= "Hello , world !";
QByteArray ba = qs1.toLocal8Bit();
const char *s = ba.data();
const char *s2 = ba.constData();

当然还可以这样:

QString qs1= "Hello , world !";
string str = qs1.toStdString();
const char *s= str.c_str();

其实就是先转为 STL 的 string 再转为 const char *.

References

  1. How can I convert a QString to char* and vice versa?
Categories: Code

Yu

Ideals are like the stars: we never reach them, but like the mariners of the sea, we chart our course by them.

5 Comments

幸福是什么意思 · January 29, 2014 at 20:09

Google Chrome 28.0.1500.95 Google Chrome 28.0.1500.95 Windows 7 Windows 7

完蛋了。,完全茫茫然。

Dzing · January 24, 2014 at 16:55

Google Chrome 30.0.1599.101 Google Chrome 30.0.1599.101 Windows XP Windows XP

真的好悬,C++的

eliteYang · January 22, 2014 at 10:19

Google Chrome 31.0.1650.57 Google Chrome 31.0.1650.57 Windows 7 x64 Edition Windows 7 x64 Edition

qstring挺好用的,不过用的最多的还是std::string

    yu · January 23, 2014 at 20:05

    Google Chrome 32.0.1700.77 Google Chrome 32.0.1700.77 GNU/Linux x64 GNU/Linux x64

    @eliteYang 只有在写Qt的时候才会用QString吧,如果不是有特别的目的的话,不怎么喜欢写Qt

博客网址之家 · January 14, 2014 at 22:13

Google Chrome 31.0.1650.63 Google Chrome 31.0.1650.63 Windows XP Windows XP

不错,没看懂的都是技术贴

Leave a Reply to Dzing Cancel reply

Your email address will not be published. Required fields are marked *