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

编写C++函数按分隔符分割字符串并返回最后一段内容

实现C++函数提取分隔字符串的最后一段

需求说明

给定以/分隔的字符串(例如"Cow eat Grass/Cat eat mouse/Dog eat meat/Fish eat worm/Snake eat mouse"),实现名为getTheLastAnimalText的函数,接收const std::string&类型参数,返回分割后的最后一段内容(示例中为"Snake eat mouse")。

实现方案

直接利用C++标准库的字符串方法即可完成,核心思路是定位最后一个分隔符的位置,再截取子串:

#include <string>

std::string getTheLastAnimalText(const std::string& source) {
    // 找到最后一个 '/' 的索引
    const size_t last_delimiter_pos = source.find_last_of('/');
    
    // 存在分隔符则截取后续子串,否则返回原字符串
    if (last_delimiter_pos != std::string::npos) {
        return source.substr(last_delimiter_pos + 1);
    }
    return source;
}

关键细节解释

  • find_last_of('/'):从字符串末尾反向查找第一个/,返回其位置;若未找到则返回std::string::npos
  • substr(pos):从指定索引pos开始截取到字符串末尾的子串,这里我们从分隔符的下一位开始,正好拿到最后一段内容
  • 边界处理:当输入字符串不含/时,直接返回原字符串,避免出现异常

测试验证

可以通过以下代码测试函数的正确性:

#include <iostream>

int main() {
    // 测试多段分隔的情况
    const std::string test_case_1 = "Cow eat Grass/Cat eat mouse/Dog eat meat/Fish eat worm/Snake eat mouse";
    std::cout << getTheLastAnimalText(test_case_1) << '\n'; // 输出: Snake eat mouse

    // 测试无分隔符的情况
    const std::string test_case_2 = "Horse eat hay";
    std::cout << getTheLastAnimalText(test_case_2) << '\n'; // 输出: Horse eat hay

    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 19:45:38