使用 QString indexOf() 方法查找子字符串 - C++ 示例

在 C++ 中,可以使用 QString 的 indexOf() 方法来搜索指定的子字符串。该方法返回子字符串在字符串中首次出现的索引位置,如果未找到则返回 -1。

示例代码:

#include <QCoreApplication>
#include <QString>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QString str = 'Hello World';
    QString searchStr = 'World';

    int index = str.indexOf(searchStr);
    if (index != -1) {
        qDebug() << '找到了指定的字串,索引位置为:' << index;
    } else {
        qDebug() << '未找到指定的字串。';
    }

    return a.exec();
}

代码解释:

  1. 包含头文件: #include <QCoreApplication>#include <QString>#include <QDebug> 用于使用 Qt 核心功能、字符串操作和调试输出。
  2. 创建字符串对象: QString str = 'Hello World';QString searchStr = 'World'; 创建两个 QString 对象,分别存储要搜索的字符串和要查找的子字符串。
  3. 调用 indexOf() 方法: int index = str.indexOf(searchStr); 使用 indexOf() 方法搜索 searchStrstr 中的位置,并将结果存储在 index 变量中。
  4. 判断结果: if (index != -1) { ... } else { ... } 检查 index 的值。如果 index 不等于 -1,则表示找到了子字符串,代码将输出其索引位置。否则,代码将输出未找到的消息。

控制台输出:

如果找到了指定的子字符串,控制台将输出:

找到了指定的字串,索引位置为: 6

如果未找到指定的子字符串,控制台将输出:

未找到指定的字串。

总结:

使用 QString 的 indexOf() 方法可以轻松地在 C++ 中查找子字符串。该方法返回子字符串的索引位置,方便你进一步处理字符串。

QString indexOf() 方法查找子字符串 - C++ 示例

原文地址: https://www.cveoy.top/t/topic/pjuU 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录