Qt QStirng 的使用

Qt的QString类提供了很方便的对字符串操作的接口。

  1. 使某个字符填满字符串,也就是说字符串里的所有字符都有等长度的ch来代替。
QString::fill ( QChar ch, int size = -1 )

例:

     QString str = "Berlin";
     str.fill('z');
     // str == "zzzzzz"

     str.fill('A', 2);
     // str == "AA"

2,从字符串里查找相同的某个字符串str。

int QString::indexOf ( const QString & str, int from = 0, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const

例如:

QString x = "sticky question";
     QString y = "sti";
     x.indexOf(y);               // returns 0
     x.indexOf(y, 1);            // returns 10
     x.indexOf(y, 10);           // returns 10
     x.indexOf(y, 11);           // returns -1

3指定位置插入字符串

QString & QString::insert ( int position, const QString & str )

例如:

     QString str = "Meal";
     str.insert(1, QString("ontr"));
     // str == "Montreal"

3,判断字符串是否为空。

bool QString::isEmpty () const

如:

     QString().isEmpty();            // returns true
     QString("").isEmpty();          // returns true
     QString("x").isEmpty();         // returns false
     QString("abc").isEmpty();       // returns false

4.判断字符串是否存在。

bool QString::isNull () const

例如:

     QString().isNull();             // returns true
     QString("").isNull();           // returns false
     QString("abc").isNull();        // returns false

5,从左向右截取字符串

QString QString::left ( int n ) const

例如:

     QString x = "Pineapple";
     QString y = x.left(4);      // y == "Pine"

6,从中间截取字符串。

QString QString::mid ( int position, int n = -1 ) const

例如:


  QString x = "Nine pineapples";
     QString y = x.mid(5, 4);            // y == "pine"
     QString z = x.mid(5);               // z == "pineapples"

7,删除字符串中间某个字符。

QString & QString::remove ( int position, int n )

例如:

     QString s = "Montreal";
     s.remove(1, 4);
     // s == "Meal"

8,替换字符串中的某些字符。

QString & QString::replace ( int position, int n, const QString & after )

例如:

     QString x = "Say yes!";
     QString y = "no";
     x.replace(4, 3, y);
     // x == "Say no!"

9,把整型,浮点型,或其他类型转化为QString

QString & QString::setNum ( uint n, int base = 10 )

相类似的还有好多重载函数,想深入了解,还是要看Qt帮助文档的。


10.1trimmed()函数用于除去串两端的空白(如空格、tab、新行):

QString str = "   BOB\t THE  \nDOG \n";

qDebug()<< str.trimmed();

str原来是

QString

 

使用trimmed()函数后返回

QString


10.2当处理用户输入时,除了去掉两端空白外,我们经常也想用一个空格替换多个内部的空白,就可用simplified()函数:

QString str = " BOB \t THE \nDOG\n";

qDebug()<< str.simplified();

使用simplified()函数后返回

QString

 


10.3从一段由特殊符号分隔的 QString 中获取被分隔的子串?

从字符串 “one, two, three, four”中获取第二个由‘,’分隔的子串,即 “two” ;
   1: #include <QtCore/QCoreApplication>
   2: #include <iostream>
   3: using namespace std;
   4:? 
   5: int main()
   6: {
   7:     QString str = "one, two, three, four";
   8:     cout << str.section(',', 1, 1).trimmed().toStdString() << endl;
   9:     return 0;
  10: }

结果是 “two”,前后不包含空格。上面的函数 trimmed() 是去掉字符串前后的ASCII字符 '\t', '\n', '\v', '\f', '\r', and ' ',这些字符用QChar::isSpace()判断都返回true。重点是 section()函数,见下面详细。
  • 从字符串 “one, two* three / four / five ^ six”中获取第四个由 ‘,’、‘*’、 ‘/’和 ‘^’分隔的子串,即“four”;
       1: #include <QtCore/QCoreApplication>
       2: #include <QRegExp>
       3: #include <iostream>
       4: using namespace std;
       5:? 
       6: int main()
       7: {
       8:     QString str = "one, two* three / four / five ^ six";
       9:     cout << str.section(QRegExp("[,*/^]"), 3, 3).trimmed().toStdString() << endl;
      10:     return 0;
      11: }
    上面用到了一个简单的正则表达式,在Qt中可以由类QRegExp构造,函数 section() 支持使用正则表达式。

QString QString::section (QChar sep, int start, int end = -1, SectionFlags flags = SectionDefault ) const

这个函数把字符串看成是几个块,这些块由 sep 分隔,startend 指定块号,end 默认为 –1 ,返回的是[start, end ]内的块组成的字符串,如果 start 和 end 都是负数,那么将从字符串的后面往前面数,返回 [-end, –start ]内的块组成的字符串。SectionFlags是一些标记,如SectionSkipEmpty表示如果两个分隔符之间是空串,那么就会跳过。下面的代码是摘自QtDoc 4.7:

  •    1: QString str;
       2: QString csv = "forename,middlename,surname,phone";
       3: QString path = "/usr/local/bin/myapp"; // First field is empty
       4: QString::SectionFlag flag = QString::SectionSkipEmpty;
       5:? 
       6: str = csv.section(',', 2, 2);   // str == "surname"
       7: str = path.section('/', 3, 4);  // str == "bin/myapp"
       8: str = path.section('/', 3, 3, flag); // str == "myapp"
       9:? 
      10: str = csv.section(',', -3, -2);  // str == "middlename,surname"
      11: str = path.section('/', -1); // str == "myapp"
  • 另外这个函数的另两个重载函数如下:
    QString QString::section ( const QString & sep, intstart, intend = -1, SectionFlags flags = SectionDefault ) const
    QString QString::section ( const QRegExp & reg, int start, int end = -1, SectionFlags flags = SectionDefault ) const

    第二个支持正则表达式作为分隔符判定,在某些场合下是不可替代的,如上面的问题中的第二个。



QStringList QString::split ( constQChar & sep, SplitBehavior behavior = KeepEmptyParts, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const

这个函数把所有的由 sep 分隔的块装进一个 QStringList 中返回, 这个函数同样有两个重载:

QStringList QString::split ( const QString &sep,SplitBehavior behavior = KeepEmptyParts, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const
QStringList QString::split ( constQRegExp & rx, SplitBehavior behavior = KeepEmptyParts ) const

使用 split() 函数对上述两个问题中的第二个进行求解:

   1: #include <QtCore/QCoreApplication>
   2: #include <QRegExp>
   3: #include <QStringList>
   4: #include <iostream>
   5: using namespace std;
   6:? 
   7: int main()
   8: {
   9:     QString str = "one, two* three / four / five ^ six";
  10:     QStringList sections = str.split(QRegExp("[,*/^]")); //把每一个块装进一个QStringList中
  11:     cout << sections.at(3).trimmed().toStdString() << endl;
  12:     return 0;
  13: }
  • 从字符串 “one, two, three, four”中获取第二个由‘,’分隔的子串,即 “two” ;
       1: #include <QtCore/QCoreApplication>
       2: #include <iostream>
       3: using namespace std;
       4:? 
       5: int main()
       6: {
       7:     QString str = "one, two, three, four";
       8:     cout << str.section(',', 1, 1).trimmed().toStdString() << endl;
       9:     return 0;
      10: }
结果是 “two”,前后不包含空格。上面的函数 trimmed() 是去掉字符串前后的ASCII字符 '\t', '\n', '\v', '\f', '\r', and ' ',这些字符用QChar::isSpace()判断都返回true。重点是 section()函数,见下面详细。
  • 从字符串 “one, two* three / four / five ^ six”中获取第四个由 ‘,’、‘*’、 ‘/’和 ‘^’分隔的子串,即“four”;
       1: #include <QtCore/QCoreApplication>
       2: #include <QRegExp>
       3: #include <iostream>
       4: using namespace std;
       5:? 
       6: int main()
       7: {
       8:     QString str = "one, two* three / four / five ^ six";
       9:     cout << str.section(QRegExp("[,*/^]"), 3, 3).trimmed().toStdString() << endl;
      10:     return 0;
      11: }
    上面用到了一个简单的正则表达式,在Qt中可以由类QRegExp构造,函数 section() 支持使用正则表达式。


QString QString::section (QChar sep, int start, int end = -1, SectionFlags flags = SectionDefault ) const

这个函数把字符串看成是几个块,这些块由 sep 分隔,startend 指定块号,end 默认为 –1 ,返回的是[start, end ]内的块组成的字符串,如果 start 和 end 都是负数,那么将从字符串的后面往前面数,返回 [-end, –start ]内的块组成的字符串。SectionFlags是一些标记,如SectionSkipEmpty表示如果两个分隔符之间是空串,那么就会跳过。下面的代码是摘自QtDoc 4.7:

  •    1: QString str;
       2: QString csv = "forename,middlename,surname,phone";
       3: QString path = "/usr/local/bin/myapp"; // First field is empty
       4: QString::SectionFlag flag = QString::SectionSkipEmpty;
       5:? 
       6: str = csv.section(',', 2, 2);   // str == "surname"
       7: str = path.section('/', 3, 4);  // str == "bin/myapp"
       8: str = path.section('/', 3, 3, flag); // str == "myapp"
       9:? 
      10: str = csv.section(',', -3, -2);  // str == "middlename,surname"
      11: str = path.section('/', -1); // str == "myapp"
  • 另外这个函数的另两个重载函数如下:
    QString QString::section ( const QString & sep, intstart, intend = -1, SectionFlags flags = SectionDefault ) const
    QString QString::section ( const QRegExp & reg, int start, int end = -1, SectionFlags flags = SectionDefault ) const

    第二个支持正则表达式作为分隔符判定,在某些场合下是不可替代的,如上面的问题中的第二个。



QStringList QString::split ( constQChar & sep, SplitBehavior behavior = KeepEmptyParts, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const

这个函数把所有的由 sep 分隔的块装进一个 QStringList 中返回, 这个函数同样有两个重载:

QStringList QString::split ( const QString &sep,SplitBehavior behavior = KeepEmptyParts, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const
QStringList QString::split ( constQRegExp & rx, SplitBehavior behavior = KeepEmptyParts ) const

使用 split() 函数对上述两个问题中的第二个进行求解:

   1: #include <QtCore/QCoreApplication>
   2: #include <QRegExp>
   3: #include <QStringList>
   4: #include <iostream>
   5: using namespace std;
   6:? 
   7: int main()
   8: {
   9:     QString str = "one, two* three / four / five ^ six";
  10:     QStringList sections = str.split(QRegExp("[,*/^]")); //把每一个块装进一个QStringList中
  11:     cout << sections.at(3).trimmed().toStdString() << endl;
  12:     return 0;
  13: }


QString str = "a,,b,c";

QStringList list1 = str.split(",");
// list1: [ "a", "", "b", "c" ]

QStringList list2 = str.split(",", QString::SkipEmptyParts);
// list2: [ "a", "b", "c" ]
list = str.split(QRegExp("\\s+"));
list = str.split(QRegExp("\\W+"));

使用jion就是逆向操作

str = list.join(",");


11,字符串连接函数
1、QString也重载的+和+=运算符。这两个运算符可以把两个字符串连接到一起。
   
2、QString的append()函数则提供了类似的操作,例如:

   str = "User: "; 
   str.append(userName); 
   str.append("\n");

  str = "User: ";  
   str.append(userName);  
   str.append("\n"); 

12,可以检测字符串是不是以某个特定的串开始或结尾。
    startsWith()    endsWith()
   
    if (url.startsWith("http:") && url.endsWith(".png")) 
         {  }

    这段代码等价于

   if (url.left(5) == "http:" && url.right(4) == ".png") 
         {  }

13,QString则提供了一个sprintf()函数实现了与C语言中的printf函数相同的功能。
   
    1. str.sprintf("%s %.1f%%", "perfect competition", 100.0);
       这句代码将输出:perfect competition 100.0%
      
    2、另一种格式化字符串输出的函数arg():
 
        str = QString("%1 %2 (%3s-%4s)").arg("permissive").arg("society").arg(1950).arg(1970);

      这段代码中,%1, %2, %3, %4作为占位符,将被后面的arg()函数中的内容依次替换,比如%1将被替换成permissive,
      %2将被替换成society,%3将被替换成 1950,%4将被替换曾1970,最后,
      这句代码输出为:permissive society (1950s-1970s). arg()函数比起sprintf()来是类型安全的,
      同时它也接受多种的数据类型作为参数,因此建议使用arg()函数而不是传统的 sprintf()。

14,求字符串的长度,返回值为INT型。
     length();// return length




  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值