首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >【Qt 比较常用的字符串处理函数】查找、比较、转换、截取、替换、插入、删除、格式化、分割、比较排序

【Qt 比较常用的字符串处理函数】查找、比较、转换、截取、替换、插入、删除、格式化、分割、比较排序

作者头像
flos chen
发布2026-01-23 15:20:29
发布2026-01-23 15:20:29
1440
举报

在Qt中,QString类提供了许多用于字符串处理的函数。以下是一些常用的字符串处理函数:

字符串查找
  • int indexOf(const QString &str, int from = 0) const:返回子字符串str在字符串中第一次出现的位置,从from位置开始查找。如果未找到,返回-1。
  • int lastIndexOf(const QString &str, int from = -1) const:返回子字符串str在字符串中最后一次出现的位置,从from位置开始反向查找。如果未找到,返回-1。
字符串比较
  • bool operator==(const QString &other) const:比较两个字符串是否相等。
  • bool operator!=(const QString &other) const:比较两个字符串是否不相等。
  • bool compare(const QString &other, Qt::CaseSensitivity cs = Qt::CaseSensitive) const:比较两个字符串,可以指定大小写敏感性。
字符串转换
  • QString toUpper() const:将字符串转换为大写。
  • QString toLower() const:将字符串转换为小写。
  • QString toTitleCase() const:将字符串转换为标题大小写(每个单词的首字母大写)。
  • QString toCaseFolded() const:将字符串转换为大小写折叠形式(用于不区分大小写的比较)。
字符串截取
  • QString left(int n) const:返回字符串的前n个字符。
  • QString right(int n) const:返回字符串的最后n个字符。
  • QString mid(int position, int n = -1) const:返回从position开始的n个字符。如果n为-1,则返回从position开始到字符串末尾的所有字符。
字符串替换
  • QString replace(int position, int n, const QString &after):替换从position开始的n个字符为字符串after
  • QString replace(const QString &before, const QString &after, Qt::CaseSensitivity cs = Qt::CaseSensitive):替换所有出现的子字符串before为字符串after,可以指定大小写敏感性。
字符串插入
  • QString insert(int position, const QString &str):在字符串的position位置插入字符串str
字符串删除
  • QString remove(const QString &str, Qt::CaseSensitivity cs = Qt::CaseSensitive):删除所有出现的子字符串str,可以指定大小写敏感性。
  • QString remove(int position, int n):删除从position开始的n个字符。
字符串格式化
  • QString arg(const QVariant &a, int fieldWidth = 0, int base = 10, const QChar &fillChar = QLatin1Char(' ')) const:使用参数替换字符串中的占位符。
字符串分割
  • QStringList split(const QString &sep, Qt::SplitBehavior behavior = Qt::KeepEmptyParts, Qt::CaseSensitivity cs = Qt::CaseSensitive) const:根据分隔符sep将字符串分割成多个子字符串,返回一个QStringList
字符串比较和排序
  • int compare(const QString &other, Qt::CaseSensitivity cs = Qt::CaseSensitive) const:比较两个字符串,返回-1、0或1,表示小于、等于或大于。
  • QStringList sorted(Qt::CaseSensitivity cs = Qt::CaseSensitive) const:返回一个排序后的字符串列表。

这些函数提供了强大的字符串处理功能,可以帮助你在Qt应用程序中轻松地进行各种字符串操作。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2026-01-23,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 字符串查找
  • 字符串比较
  • 字符串转换
  • 字符串截取
  • 字符串替换
  • 字符串插入
  • 字符串删除
  • 字符串格式化
  • 字符串分割
  • 字符串比较和排序
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档