QString用法總結

構造QString

在 Qt 中如何構造一段格式化字符串?

當然,C 中的方法都是可行的,比如 stdio.h 裏面的 snprintf 什麼的。在 Qt 中QString 提供了更好用的函數。

  • arg

這個函數的具體聲明不寫了,它有20個重載,典型的示例代碼如下:

   1: #include <QtCore/QCoreApplication>
   2: #include <iostream>
   3: #include <stdio.h>
   4: using namespace std;
   5: 
   6: int main()
   7: {
   8:     QString str = QString("Ggicci is %1 years old, and majors in %2.").arg(20).arg("Software Eng");
   9:     cout << str.toStdString() << endl;
  10:     return 0;
  11: }
輸出結果:
Ggicci is 20 years old, and majors in Software Eng.
Press <RETURN> to close this window...

上面代碼中的字符串 “Ggicci is %1 years old, and majors in %2.” 中的 %1 和 %2 爲佔位符,後面跟隨的兩個 arg() 函數中的參數分別對應兩個佔位符作爲值插入。這種形式在 C# 中也有類似的體現(C#中輸出一段文字):

Console.WriteLine("Ggicci is {0} years old, and majors in {1}.", 20, "Software Eng");

  • sprintf
  • QString & QString::sprintf ( const char * cformat, ... )

    這個函數和 C 中的也是差不多的用法,只不過它作爲QString的一個成員函數,使用起來就相當方便了,如:

       1: #include <QtCore/QCoreApplication>
       2: #include <iostream>
       3: #include <stdio.h>
       4: using namespace std;
       5: int main()
       6: {
       7:     QString str2;
       8:     str2.sprintf("Ggicci is %d years old, and majors in %s.", 20, "Software Eng");
       9:     cout << str2.toStdString() << endl;
      10:     return 0;
      11: }

輸入結果:

Ggicci is 20 years old, and majors in Software Eng.
Press <RETURN> to close this window...


qDebug()用法

首先在頭文件中包含#include <QDebug>

在需要使用的地方插入:

         qDebug("intensity:%d",intensity[0][2]); (%d表示整數)

輸出結果:

intensity:195

qDebug使用形式:

1、qDebug()<< 

如:

int nDebug;

QString strDebug;

qDebug()<< "This is for debug, nDebug="<<nDebug<<", strDebug="<<strDebug;

2、qDebug(字符串格式,格式替換實際值)

qDebug("This is for Debug, nDebug=%n, strDebug=%s", nDebug, QByteArray(strDebug.toLatin1).data());

用.sprintf()以及.arg()函數組成字符串輸出亦可。 

字符串格式說明:
%a,%A 讀入一個浮點值(僅C99有效)    
%c 讀入一個字符    
%d 讀入十進制整數    
%i 讀入十進制,八進制,十六進制整數    
%o 讀入八進制整數    
%x,%X 讀入十六進制整數   
%s 讀入一個字符串,遇空格、製表符或換行符結束。
注意:爲了防止字符串中間有空格而停止,可以使用(“%s”,QByteArray(str.toLatin1()).data())格式,將字符串轉換爲字符數組形式。    
%f,%F,%e,%E,%g,%G 用來輸入實數,可以用小數形式或指數形式輸入。    
%p 讀入一個指針    
%u 讀入一個無符號十進制整數   
%n 至此已讀入值的等價字符數    
%[] 掃描字符集合    

%% 讀%符號


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章