【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/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM