【QT学习】字符串和数字

作者:gnuhpc
出处:http://www.cnblogs.com/gnuhpc/

这两部分在任何一个框架或者叫做程序库中都是很基础且重要的部分,我们看看QT这方面的东西。

QT的字符串类是QString,而QStringList则是一个string列表的数据结构。你不需要去关心内存分配问题,QT会为你处理这一切的。

String在内部是以unicode为编码的,在转到8bit时,我们需要使用toAscii()toLatin1()方法。

在字符串与数字转换中,提供了toInt()和toDouble()。其中还提供了对于操作是否成功的判断,例如:

int hex = str.toInt(&ok, 16);       // hex == 255, ok == true

数字转到字符串则是如下一些操作:

// integer converstion
QString str;
str.setNum(1234);  // str now contains "1234"
// double converstion
double d = 2.345;
str.setNum(d);  // default format ("g"), default precision is 6, str is now "2.345000"
str.setNum(d, 'f', 3);  // "2.345"
str.setNum(d, 'e', 3);  // "2.345e+00"

int myInt = 123;
QMessageBox(this, "Some label", "Hello, value of integer called myInt is " + QString::number(myInt) );

QStringList 则更好用:

QStringList list;
 
// add string into the list
// these 3 ways of adding string to list are equivalent
list.append("apple");
list += "banana";
list << "submarine";
 
// iterate over string list
QString str;
for (int i = 0; i < list.size(); ++i)
{
    str = list[i]; // or list.at(i);
    // do something with str
}

作者:gnuhpc
出处:http://www.cnblogs.com/gnuhpc/


               作者:gnuhpc
               出处:http://www.cnblogs.com/gnuhpc/
               除非另有声明,本网站采用知识共享“署名 2.5 中国大陆”许可协议授权。


分享到:

原文地址:https://www.cnblogs.com/gnuhpc/p/2811956.html