qt QString常用函数simplified replace remove split indexOf mid left right prepend repeated number arg

本文详细解析了QString类中常用函数的功能与用法,包括simplified、replace、remove、split等,通过实例展示了如何进行字符串处理,适用于Qt开发人员深入理解和高效应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以下是QString常用函数使用过程中的总结,例子大多数摘抄自qt自带的帮助文档

1、simplified

simplified()功能,这个函数把一个字符串首尾的空格全部清除,不管首尾是几个空格哦。字符串中间的空格(包括单个空格、多个空格、\t、\n)都统一转化成一个空格,这样就方便提取了,我们再使用split()函数就能很好拆分了。

qt帮助文档介绍.

QString QString::simplified() const

Returns a string that has whitespace removed from the start and the end, and that has each sequence of internal whitespace replaced with a single space.

Whitespace means any character for which QChar::isSpace() returns true. This includes the ASCII characters '\t', '\n', '\v', '\f', '\r', and ' '.

Example:

  QString str = "  lots\t of\nwhitespace\r\n ";
  str = str.simplified();
  // str == "lots of whitespace";

See also trimmed().

 

2、replace

字符替换,replace有很大重载函数这里只摘抄一个。

qt帮助文档介绍.

QString &QString::replace(const QString &before, const QString &after, Qt::CaseSensitivity cs = Qt::CaseSensitive)

This function overloads replace().

Replaces every occurrence of the string before with the string after and returns a reference to this string.

If cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.

Example:

  QString str = "colour behaviour flavour neighbour";
  str.replace(QString("ou"), QString("o"));
  // str == "color behavior flavor neighbor"
Note: The replacement text is not rescanned after it is inserted.

Example:

  QString equis = "xxxxxx";
  equis.replace("xx", "x");
  // equis == "xxx"

3、remove

字符串移除,remove同样的也有很大重载函数,这里只说有一个,就是移除从第position开始的n个字符

qt帮助文档介绍.

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

Removes n characters from the string, starting at the given position index, and returns a reference to the string.

If the specified position index is within the string, but position + n is beyond the end of the string, the string is truncated at the specified position.

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

See also insert() and replace().

4、split

字符串分割,remove同样的也有很大重载函数,这里只摘抄一个

qt帮助文档介绍.

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

Splits the string into substrings wherever sep occurs, and returns the list of those strings. If sep does not match anywhere in the string, split() returns a single-element list containing this string.

cs specifies whether sep should be matched case sensitively or case insensitively.

If behavior is QString::SkipEmptyParts, empty entries don't appear in the result. By default, empty entries are kept.

Example:

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

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

  QStringList list2 = str.split(',', QString::SkipEmptyParts);
  // list2: [ "a", "b", "c" ]
See also QStringList::join() and section().

5、indexOf

字符串查找/截取,indexOf同样的也有很大重载函数,这里只摘抄一个,查找到第一个匹配的字符串,如果找不到返回-1.

qt帮助文档介绍.

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

Returns the index position of the first occurrence of the string str in this string, searching forward from index position from. Returns -1 if str is not found.

If cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.

Example:

  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

6、mid

截取从n个字符串,重position开始截取,截取n个字符串,如果n默认为-1,为-1代表从position开始截取,截取到字符串结束。

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

Returns a string that contains n characters of this string, starting at the specified position index.

Returns a null string if the position index exceeds the length of the string. If there are less than n characters available in the string starting at the given position, or if n is -1 (default), the function returns all characters that are available from the specified position.

Example:

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

7、left

从左边开始截取n个字符串

QString QString::left(int n) const

Returns a substring that contains the n leftmost characters of the string.

The entire string is returned if n is greater than or equal to size(), or less than zero.

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

8、right

从右边开始截取n个字符串

QString QString::right(int n) const

Returns a substring that contains the n rightmost characters of the string.

The entire string is returned if n is greater than or equal to size(), or less than zero.


  QString x = "Pineapple";
  QString y = x.right(5);      // y == "apple"

8、prepend

在头部追加字符串

QString &QString::prepend(const QString &str)

Prepends the string str to the beginning of this string and returns a reference to this string.

Example:

  QString x = "ship";
  QString y = "air";
  x.prepend(y);
  // x == "airship"

9、repeated

重复字符串

QString QString::repeated(int times) const

Returns a copy of this string repeated the specified number of times.

If times is less than 1, an empty string is returned.

Example:

  QString str("ab");
  str.repeated(4);            // returns "abababab"

10、number

多重载函数,字符串和数值之间的转换,可以是10进制或者16进制。

[static] QString QString::number(long n, int base = 10)

Returns a string equivalent of the number n according to the specified base.

The base is 10 by default and must be between 2 and 36. For bases other than 10, n is treated as an unsigned integer.

The formatting always uses QLocale::C, i.e., English/UnitedStates. To get a localized string representation of a number, use QLocale::toString() with the appropriate locale.

  long a = 63;
  QString s = QString::number(a, 16);             // s == "3f"
  QString t = QString::number(a, 16).toUpper();     // t == "3F"
   
  QString r = QString::number(a,'f',2);            //2代表保留2位小数,63.00 
  QString u = QString::number(a).sprintf("%2d",a)  //d代表整数,2代表两位,sprintf和printf有点类似,a格式化成两位整数(不会自动补零)

    
   strNumber = strNumber.sprintf("%02d:%02d:%02d", hour, minute, seconds);//%02d:0代表补位的值为零、2表示位数。

11、sprintf

格式化输出

QString str;
str.sprintf("%s","Welcome ");     //str = "Welcome "
str.sprintf("%s"," to you! ");      //str = " to you! "
str.sprintf("%s %s","Welcome "," to you! ");     //str = "Welcome  to you! ";
QString u = QString::number(a).sprintf("%2d",a)  //d代表整数,2代表两位,sprintf和printf有点类似,a格式化成两位整数(不会自动补零)
strNumber = strNumber.sprintf("%02d:%02d:%02d", hour, minute, seconds);//%02d:0代表补位的值为零、2表示位数。

12、arg

arg的重载函数也特别多,

QString QString::arg(long a, int fieldWidth = 0, int base = 10, QChar fillChar = QLatin1Char( ' ' )) const

This function overloads arg().

fieldWidth specifies the minimum amount of space that a is padded to and filled with the character fillChar. A positive value produces right-aligned text; a negative value produces left-aligned text.

The a argument is expressed in the given base, which is 10 by default and must be between 2 and 36.

The '%' can be followed by an 'L', in which case the sequence is replaced with a localized representation of a. The conversion uses the default locale. The default locale is determined from the system's locale settings at application startup. It can be changed using QLocale::setDefault(). The 'L' flag is ignored if base is not 10.

  QString str;
  str = QString("Decimal 63 is %1 in hexadecimal")
          .arg(63, 0, 16);
  // str == "Decimal 63 is 3f in hexadecimal"

  QLocale::setDefault(QLocale(QLocale::English, QLocale::UnitedStates));
  str = QString("%1 %L2 %L3")
          .arg(12345)
          .arg(12345)
          .arg(12345, 0, 16);
  // str == "12345 12,345 3039"

If fillChar is '0' (the number 0, ASCII 48), the locale's zero is used. For negative numbers, zero padding might appear before the minus sign.

 

不足补零

int num = 1;

QString("%1").arg(num,2, 10, QChar('0'));

这样输出的就是01.

其中2代表要输出几位,10代表10进制转换,QChar('0')代表不足补0(可以更换成你自己想要的字母)

还有好多函数,今天就先写到这吧

另外还可以参考:

https://blog.csdn.net/asd1147170607/article/details/105630837

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值