You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C++内置方法获取字符串中首个子串的最后索引?

如何用C++内置方法获取匹配子串最后一个字符的索引

直接利用std::string::find(或rfind)的返回值结合子串长度就能实现,不需要额外复杂操作:

  1. 先用find获取目标子串的起始索引,记得用size_t类型存储(这是find的返回类型,避免类型错误)
  2. 检查是否找到子串(判断返回值不等于std::string::npos)
  3. 最后一个字符的索引 = 起始索引 + 子串长度 - 1

示例代码

#include <string>
#include <iostream>

int main() {
    std::string str = "Hey I'm John, John's friend";
    const std::string target = "John";
    
    // 获取首个"John"的起始位置
    size_t start_pos = str.find(target);
    
    if (start_pos != std::string::npos) {
        size_t last_char_idx = start_pos + target.length() - 1;
        std::cout << "首个'John'最后一个字符的索引: " << last_char_idx << std::endl;
    } else {
        std::cout << "未找到目标子串" << std::endl;
    }

    // 如果要找最后一个出现的"John"的最后一个字符
    size_t last_start_pos = str.rfind(target);
    if (last_start_pos != std::string::npos) {
        size_t last_char_idx = last_start_pos + target.length() - 1;
        std::cout << "最后一个'John'最后一个字符的索引: " << last_char_idx << std::endl;
    }
    return 0;
}

关键注意点

  • 别用int存索引:std::string的索引类型是size_t(无符号整数),用int可能会导致负数判断错误或者溢出。
  • 必须先检查子串是否存在:如果find返回std::string::npos(表示未找到),直接计算会得到错误结果。

内容的提问来源于stack exchange,提问作者Pal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 07:45:32