Qt学习(5)——Qt5中的String(4)

  • 字符
  • 修改字符串
  • 字符串对齐
  • 转义字符

字符

字符分为各种类别:数字,字母,空格和标点符号。QString由QChars组成。QChar用于isDigit(),isLetter(), isSpace()isPunct()方法。

// letters.cpp

#include 

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.";

  foreach(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;
}

在这个例子中我们将统计字母、数字、空格、标点的累计数量。

foreach(QChar s, str) {

  if (s.isDigit()) {
    digits++;
  } else if (s.isLetter()) {
    letters++;
  } else if (s.isSpace()) {
    spaces++;
  } else if (s.isPunct()) {
    puncts++;
  }    
} 

采用foreach遍历整个字符串,然后用isDigit()判断是否是数字,用isLetter()判断是否是字母,用isSpace()判断是否是空格,用isPunct()判断是否是标点。
输出结果为:

$ ./letters 
There are 21 characters
There are 13 letters
There are 2 digits
There are 4 spaces
There are 2 punctuation characters

修改字符串

一些方法(例如tolower()方法)会返回原始字符串的新修改副本。其他的一些方法就地修改字符串。

// modify.cpp

#include 

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;
}
str.append(" season");

在字符串后面添加字符串。

str.remove(10, 3);

从字符串第十个字符开始移除三个字符。

str.replace(7, 3, "girl");

用特定字符串替换原有字符串的第七个字符开始的三个字符。

str.clear();

清空字符串内容。
输出结果:

$ ./modify 
Lovely season
Lovely sea
Lovely girl
The string is empty

字符串对齐

使用leftJustified()rightJustified()方法来对齐字符串。

// right_align.cpp
#include 

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;
}

该示例将字段字符串对齐到右侧。

   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";

rightJustified() 方法返回一个具有width字符的字符串。如果字符串较短,其余部分填充所提供的字符。在我们的例子中,它是一个空格字符。
输出结果为:

$ ./right_align 
          Name: Robert
    Occupation: programmer
     Residence: New York
Marital status: single

转义字符

Qt5有一个toHtmlEscaped()方法,它将纯文本字符串转换为带有HTML元字符<>"的HTML字符串,并由HTML命名实体替换。

$ cat cprog.c 
#include 

int main(void) {

    for (int i=1; i<=10; i++) {
        printf("Bottle %d\n", i);
    }
}

这个c程序包含HTML元字符。

// html_escape.cpp
#include 
#include 

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);

    QString allText = in.readAll();    
    out << allText.toHtmlEscaped() << endl;

    file.close();

    return 0;

该示例读取一个c程序并用它们的命名实体替换元字符。
如果直接运行qmake -project,生成的.pro文件内容如下:

 ######################################################################
 # Automatically generated by qmake (3.1) Mon Feb 12 19:47:55 2018
 ######################################################################

 TEMPLATE = app
 TARGET = html_escape
 INCLUDEPATH += .

 # The following define makes your compiler warn you if you use any
 # feature of Qt which has been marked as deprecated (the exact warnings
 # depend on your compiler). Please consult the documentation of the
 # deprecated API in order to know how to port your code away from it.
 DEFINES += QT_DEPRECATED_WARNINGS

 # You can also make your code fail to compile if you use deprecated APIs.
 # In order to do so, uncomment the following line.
 # You can also select to disable deprecated APIs only up to a certain version of Qt.
 #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000   
 # disables all the APIs deprecated before Qt 6.0.0

 # Input
 SOURCES += cprog.c html_escape.cpp

需要在最后一行加上QT -= gui,然后执行qmakemake命令会报如下错误:

...
html_escape.o:在函数‘main’中:
html_escape.cpp:(.text.startup+0x0): main 的多重定义
cprog.o:cprog.c:(.text.startup+0x0):第一次在此定义
collect2: error: ld returned 1 exit status
Makefile:248: recipe for target 'html_escape' failed
make: *** [html_escape] Error 

解决方法为将.pro文件中SOURCES += cprog.c html_escape.cpp改为SOURCES += html_escape.cpp,再执行make即可。

输出结果为:

$ ./html_escape 
#include <stdio.h>

int main(void) {

    for (int i=1; i&lt;=10; i++) {
        printf("Bottle %d\n", i);
    }
}

你可能感兴趣的:(Qt)