Skip to main content
 首页 » 编程设计

C++ 字符串类应用教程

2022年07月19日173exmyth

本文介绍Qt5中的QString类,它主要实现字符串相关的功能,提供了很多强大的方法。QString类支持Unicode字符编码,按照16字节QChar方式存储字符串,每个QCharr对应一个Unicode 4.0字符。与其他语言不同,QStrring能够被修改。
本文提供的示例不需要Qt GUI模块,创建为命令行程序示例。因为Qt GUI模块是缺省加载的,因此需要通过 QT -= gui 进行显示声明。

基础示例

首先我们看QString类的一些基础方法:

#include <QTextStream> 
 
int main(void) { 
   QTextStream out(stdout); 
 
   // 初始化字符串对象 
   QString a { "love" }; 
 
   // 后面追加字符串 
   a.append(" chess"); 
   // 前面追加字符串 
   a.prepend("I "); 
 
   out << a << endl; 
 
   // 查看字符串包括字符数量 
   out << "The a string has " << a.count() 
       << " characters" << endl; 
 
   // 转大小写 
   out << a.toUpper() << endl; 
   out << a.toLower() << endl; 
 
   return 0; 
} 

输出结果:

I love chess 
The a string has 12 characters 
I LOVE CHESS 
i love chess 

初始化字符串

QString 支持多种方法字符串对象:

#include <QTextStream> 
 
int main(void) { 
 
   QTextStream out(stdout); 
 
   // 传统方式,与其他语言类似 
   QString str1 = "The night train"; 
   out << str1 << endl; 
 
   // 初始化对象方式 
   QString str2("A yellow rose"); 
   out << str2 << endl; 
 
   // 使用花括号方式 
   QString str3 {"An old falcon"}; 
   out << str3 << endl; 
 
   // C++ 标准库的字符串对象,通过c_str方法转为无终止标志字符序列 
   // 然后直接把经典C形式的字符数组赋值给QString对象 
   std::string s1 = "A blue sky"; 
   QString str4 = s1.c_str(); 
   out << str4 << endl; 
 
   // 利用fromLatin1方法转换C++标准库字符串为QString对象 
   // std::string的data方法返回字符数组的指针,第二个参数是数组大小 
   std::string s2 = "A thick fog"; 
   QString str5 = QString::fromLatin1(s2.data(), s2.size()); 
   out << str5 << endl; 
 
   // C 字符串,即字符数组,可以直接调用QString构造函数初始化 
   char s3[] = "A deep forest"; 
   QString str6(s3); 
   out << str6 << endl; 
 
   return 0; 
} 

输出结果:

The night train 
A yellow rose 
An old falcon 
A blue sky 
A thick fog 
A deep forest 

访问字符串元素

QString是一组QChar的序列。可以通过[] 操作符访问字符串元素:

#include <QTextStream> 
 
int main(void) { 
 
   QTextStream out(stdout); 
 
   QString a { "Eagle" }; 
 
   // 输出第1、5两个位置的字符 
   out << a[0] << endl; 
   out << a[4] << endl; 
 
   // at 方法访问第一个字符 
   out << a.at(0) << endl; 
 
   // 超出字符序列范围,at方法返回null 
   if (a.at(5).isNull()) { 
     out << "Outside the range of the string" << endl; 
   } 
 
   return 0; 
} 

输出结果:

E 
e 
E 
Outside the range of the string 

字符串长度

有三个方法返回字符串长度,size、count、length方法。三者作用相同,返回特定字符串字符数量。需要说明的白色空格以及回车符也被计算,另外由于使用Unicode编码,每个汉字算作一个字符:

#include <QTextStream> 
 
int main(void) { 
 
  QTextStream out(stdout); 
 
  QString s1 = "Eagle"; 
  QString s2 = "Eagle\n"; 
  QString s3 = "Eagle "; 
  QString s4 = "ореn"; 
 
  out << s1.length() << endl; 
  out << s2.length() << endl; 
  out << s3.length() << endl; 
  out << s4.length() << endl; 
 
  return 0; 
} 

输出结果:

5 
6 
6 
4 

构建字符串

动态构建字符串,可以使用实际值代替控制字符,arg方法进行插入替换。
以%开头的字符标记会被替换,可以包括多个字符标记。arg方法有多个重载方法,支持数值(integer,long,char、QChar等)。

#include <QTextStream> 
 
int main() { 
 
   QTextStream out(stdout); 
 
   // 定义字符串模板 
   QString s1 = "There are %1 white roses"; 
   int n = 12; 
 
   out << s1.arg(n) << endl; 
 
   QString s2 = "The tree is %1 m high"; 
   double h = 5.65; 
 
   out << s2.arg(h) << endl; 
 
   // 支持多个控制字符,%1引用第一个字符,%2引用第二个字符 
   QString s3 = "We have %1 lemons and %2 oranges"; 
   int ln = 12; 
   int on = 4; 
 
   // arg支持链式调用 
   out << s3.arg(ln).arg(on) << endl; 
 
   return 0; 
} 

输出结果:

There are 12 white roses 
The tree is 5.65 m high 
We have 12 lemons and 4 oranges 

取子串

字符串过程中,需要查找字符串中的子串。left、mid、right方式可供选择:

#include <QTextStream> 
 
int main(void) { 
 
   QTextStream out(stdout); 
   QString str = { "The night train" }; 
 
   // 从右取5个 
   out << str.right(5) << endl; 
 
   // 从左取9个 
   out << str.left(9) << endl; 
 
   // 从中间第四个开始,取5个 
   out << str.mid(4, 5) << endl; 
 
   // sub方法实现通用功能 
   QString str2("The big apple"); 
   QStringRef sub(&str2, 0, 7); 
 
   out << sub.toString() << endl; 
 
   return 0; 
} 

输出结果:

train 
The night 
night 
The big 

遍历字符串

QString字符串有QChar组成,可以通过不同方式遍历字符串每个元素:

#include <QTextStream> 
 
int main(void) { 
 
  QTextStream out(stdout); 
  QString str { "There are many stars." }; 
 
  // 基于范围方式遍历 
  for (QChar qc: str) { 
    out << qc << " "; 
  } 
 
  out << endl;  
 
  // 使用迭代器遍历 
  for (QChar *it=str.begin(); it!=str.end(); ++it) { 
    out << *it << " " ; 
  } 
 
  out << endl; 
 
  // 利用size进行遍历 
  for (int i = 0; i < str.size(); ++i) { 
    out << str.at(i) << " "; 
  } 
 
  out << endl; 
 
  return 0; 
} 

输出结果:

T h e r e   a r e   m a n y   s t a r s . 
T h e r e   a r e   m a n y   s t a r s . 
T h e r e   a r e   m a n y   s t a r s . 

字符串比较

QString::compare 静态方法用于比较字符串,返回值为整数。0表示相对,小于0表示第一个字符串小于第二个,大于0则相反。

这里的’小于’是指字符串中的一个特定字符在字符表中被定位在另一个字符之前。字符串的比较方法如下:比较两个字符串的第一个字符;如果它们相等,则比较后面两个字符,直到找到一些不同的字符,或者找到所有字符都匹配。

#include <QTextStream> 
 
#define STR_EQUAL 0 
 
int main(void) { 
 
   QTextStream out(stdout); 
 
   QString a { "Rain" }; 
   QString b { "rain" }; 
   QString c { "rain\n" }; 
 
   if (QString::compare(a, b) == STR_EQUAL) { 
     out << "a, b are equal" << endl; 
   } else { 
     out << "a, b are not equal" << endl; 
   } 
 
   out << "In case insensitive comparison:" << endl; 
 
   // 大小写不敏感 
   if (QString::compare(a, b, Qt::CaseInsensitive) == STR_EQUAL) { 
     out << "a, b are equal" << endl; 
   } else { 
     out << "a, b are not equal" << endl; 
   } 
 
   if (QString::compare(b, c) == STR_EQUAL) { 
     out << "b, c are equal" << endl; 
   } else { 
     out << "b, c are not equal" << endl; 
   } 
 
   // 从末尾删除n个字符 
   c.chop(1); 
 
   out << "After removing the new line character" << endl; 
 
   // 删除回车符后进行比较 
   if (QString::compare(b, c) == STR_EQUAL) { 
     out << "b, c are equal" << endl; 
   } else { 
     out << "b, c are not equal" << endl; 
   } 
 
   return 0; 
} 

输出结果:

a, b are not equal 
In case insensitive comparison: 
a, b are equal 
b, c are not equal 
After removing the new line character 
b, c are equal 

字符串转换

有时字符串需要被转换为其他数据类型,反之亦然。 toInt, toFloat, toLong 方法用于转换字符串为数值类型。setNum方法用于转换数值为字符串类型,另外它还有其他重载方法。

#include <QTextStream> 
 
int main(void) { 
 
  QTextStream out(stdout); 
 
  QString s1 { "12" }; 
  QString s2 { "15" }; 
  QString s3, s4; 
 
  // 字符串转为整数并相加 
  out << s1.toInt() + s2.toInt() << endl; 
 
  int n1 = 30; 
  int n2 = 40; 
 
  // 数值转为字符串并连接起来 
  out << s3.setNum(n1) + s4.setNum(n2) << endl; 
 
  return 0; 
} 

输出结果:

27 
3040 

字符类型

字符分为不同类型:数字、字母、空格以及标点符号。字符串由QChar组成,QChar提供了isDigit, isLetter, isSpace, isPunct 判断字符类型。
在这里插入图片描述

#include <QTextStream> 
 
int main(void) { 
 
  QTextStream out(stdout); 
 
  int digits  = 0; 
  int letters = 0; 
  int spaces  = 0; 
  int puncts  = 0; 
 
  QString str { "7 white, 3 red roses." }; 
 
  // 遍历字符串,分别统计数字、字母、空格以及标点字符的数量 
  for (QChar s : str) { 
    if (s.isDigit()) { 
      digits++; 
    } else if (s.isLetter()) { 
      letters++; 
    } else if (s.isSpace()) { 
      spaces++; 
    } else if (s.isPunct()) { 
      puncts++; 
    } 
  } 
 
  out << QString("There are %1 characters").arg(str.count()) << endl; 
  out << QString("There are %1 letters").arg(letters) << endl; 
  out << QString("There are %1 digits").arg(digits) << endl; 
  out << QString("There are %1 spaces").arg(spaces) << endl; 
  out << QString("There are %1 punctuation characters").arg(puncts) << endl; 
 
  return 0; 
} 

输出结果:

There are 21 characters 
There are 13 letters 
There are 2 digits 
There are 4 spaces 
There are 2 punctuation characters 

修改字符串

前面我们使用了toLower方法把字符串转为小写形式,下面看看其他一些修改方法:

#include <QTextStream> 
 
int main(void) { 
 
   QTextStream out(stdout); 
 
   // 追加字符串 
   QString str { "Lovely" }; 
   str.append(" season"); 
 
   out << str << endl; 
 
   // 删除字符 
   str.remove(10, 3); 
   out << str << endl; 
 
   // 替换 
   str.replace(7, 3, "girl"); 
   out << str << endl; 
 
   // 清除字符串 
   str.clear(); 
 
   if (str.isEmpty()) { 
     out << "The string is empty" << endl; 
   } 
 
   return 0; 
} 

输出结果:

Lovely season 
Lovely sea 
Lovely girl 
The string is empty 

字符串对齐

有时需要对字符串按照整洁的格式输出,如左对齐、右对齐。

#include <QTextStream> 
 
int main(void) { 
 
   QTextStream out(stdout); 
 
   QString field1 { "Name: " };  
   QString field2 { "Occupation: " };  
   QString field3 { "Residence: " };  
   QString field4 { "Marital status: " };  
 
   int width = field4.size(); 
 
   // 按照右对齐方式输出标题 
   out << field1.rightJustified(width, ' ') << "Robert\n"; 
   out << field2.rightJustified(width, ' ') << "programmer\n"; 
   out << field3.rightJustified(width, ' ') << "New York\n"; 
   out << field4.rightJustified(width, ' ') << "single\n"; 
 
   return 0; 
} 

输出结果:

          Name: Robert 
    Occupation: programmer 
     Residence: New York 
Marital status: single 

转义字符

Qt5提供toHtmlEscaped方法,能够转换普通文本为html文本。html文本把特殊字符(<,>,& ")转为命名实体。

下面C程序文件作为示例文件进行转换:

$ cat cprog.c 
#include <stdio.h> 
 
int main(void) { 
 
    for (int i=1; i<=10; i++) { 
       
        printf("Bottle %d\n", i); 
    } 
} 

文件中其中包括 <, >, <=, ", % 多个特殊字符。

#include <QTextStream> 
#include <QFile> 
 
int main(void) { 
 
    QTextStream out(stdout); 
    QFile file("cprog.c"); 
 
    // 打开文件 
    if (!file.open(QIODevice::ReadOnly)) { 
        qWarning("Cannot open file for reading"); 
        return 1; 
    } 
 
    // 读文本文件流 
    QTextStream in(&file); 
 
    // 转为Html格式,特殊字符进行转义 
    QString allText = in.readAll(); 
    out << allText.toHtmlEscaped() << endl; 
 
    file.close(); 
 
    return 0; 
} 

输出结果:

#include &lt;stdio.h&gt; 
 
int main(void) { 
 
    for (int i=1; i&lt;=10; i++) { 
        printf(&quot;Bottle %d\n&quot;, i); 
    } 
} 

本文参考链接:https://blog.csdn.net/neweastsun/article/details/123879709