QT5 String
初始字串的 5 個方式
QString str1 = "The night train";//
QT
常見初始方式
QString str2("A yellow rose");
//
QT
常見初始方式
std::string s1 = "A blue sky"; // C++標準library
QString str3 = s1.c_str(); // 把string物件轉換成C語言形式的字串常數
std::string s2 = "A thick fog";
QString str4 = QString::fromLatin1(s2.data(), s2.size()); //將C++string轉換成Qstring
char s3[] = "A deep forest";
QString str5(s3); //將C 字符陣列轉換成QString
取得單一字符
QString a = "Eagle";
a[0]; //output "E"
a.at(0); //
output "E"
字串長度
QString s1 = "Eagle";
s1.size(); // 5
s1.count(); // 5
s1.length(); // 5
字串取代
QString s1 = "There are %1 white roses";
s1.arg(12); // There are 12 white roses
QString s2 = "We have %1 lemons and %2 oranges";
s2.arg("one").arg("two");// We have one lemons and two oranges
擷取字串
QString str = "The night train";
str.right(5); //從右邊開始擷取5個字符
str.left(9); //從左邊開始擷取9個字符
str.mid(4, 5); //從第4個字符開始,取5個字符
QString str2("The big apple");
QStringRef sub(&str2, 0, 7); //從第0個字符開始,擷取7個字符
sub.toString(); //QStringRef class 只能讀不能修改,需轉成string
字串遍歷
QTextStream out(stdout);
QString str = "There are many stars.";
foreach (QChar qc, str) {
out << qc << " ";
}
for (QChar *it=str.begin(); it!=str.end(); ++it) {
out << *it << " " ;
}
//begin() 取得指向的開始位置
for (int i = 0; i < str.size(); ++i) {
out << str.at(i) << " ";
}
Output
T h e r e a r e m a n y s t a r s .
字串比較
QString a = "Rain";
QString b = "rain";
QString c = "rain\n";
QString::compare(a, b) == -32
QString::compare(a, b, Qt::CaseInsensitive) == 0
字串轉換
QString s1 = "12";
QString s2 = "15";
QString s3, s4;
s1.toInt() + s2.toInt() //27
int n1 = 30;
int n2 = 40;
s3.setNum(n1) + s4.setNum(n2) //3040
字串屬性
int digits = 0;
int letters = 0;
int spaces = 0;
int puncts = 0;
QString str = "7 white, 3 red roses.";
foreach(QChar s, str) {
if (s.isDigit()) {
digits++;
} else if (s.isLetter()) {
letters++;
} else if (s.isSpace()) {
spaces++;
} else if (s.isPunct()) {
puncts++;
}
}
// 2 digits
// 13
letters
// 4 spaces
// 2
puncts 標點
字串編輯
QString str = "Lovely";
str.append(" season"); //在尾巴加入字串 Lovely season
str.remove(10, 3); //從第10字元開始,刪除3個字元 Lovely sea
str.replace(7, 3, "girl"); //從第7字元開始,取代字串 Lovely girl
str.clear(); // 清除字串
str.isEmpty(); //true
str.chop(1); //刪除最後第1個字元
字串對齊
leftJustified()/rightJustified()
QString field1 = "Name: ";
QString field2 = "Occupation: ";
QString field3 = "Residence: ";
QString field4 = "Marital status: ";
//取最長字串長度,填滿' '空白
int wSpace = field4.size();
out << field1.rightJustified(wSpace, ' ') << "Robert\n";
out << field2.rightJustified(wSpace, ' ') << "programmer\n";
out << field3.rightJustified(wSpace, ' ') << "New York\n";
out << field4.rightJustified(wSpace, ' ') << "single\n";
Output
Name: Robert
Occupation: programmer
Residence: New York
Marital status: single
HTML跳脫字元
QFile file("cprog.c");
if (!file.open(QIODevice::ReadOnly)) {
qWarning("Cannot open file for reading");
return 1;
}
QTextStream in(&file);
QString allText = in.readAll();
out << allText.toHtmlEscaped() << endl; //取代<, >, &
file.close();
參考: