【Qt 比较常用的字符串处理函数】查找、比较、转换、截取、替换、插入、删除、格式化、分割、比较排序
在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应用程序中轻松地进行各种字符串操作。