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

C++如何获取stringstream的最后一个元素?提取作者姓氏需求

提取完整姓名中的姓氏

你的代码问题在于std::stringstream的迭代器并非随机访问迭代器,不能用end() - 1这类操作,而且它本身不会将所有分词存储为可直接索引的集合。下面提供两种简单可行的解决方法:

方法一:利用stringstream逐个读取,保留最后一个分词

这个思路和你最初的想法接近,只需循环读取所有分词,每次更新last_name,最后剩下的就是姓氏:

#include <sstream>
#include <string>

std::string get_last_name(const std::string& full_name) {
    std::stringstream stream(full_name);
    std::string last_name;
    // 逐个读取所有分词,最后一次赋值的结果就是姓氏
    while (stream >> last_name) {}
    return last_name;
}

如果输入的姓名只有单个词(比如"Einstein"),这个方法也能直接返回正确结果。

方法二:直接操作std::string,定位最后一个空格

不需要借助stringstream,直接通过字符串操作找到最后一个空格的位置,再截取子串即可:

#include <string>

std::string get_last_name(const std::string& full_name) {
    // 定位最后一个空格的位置
    size_t last_space_pos = full_name.find_last_of(' ');
    // 没有空格说明是单字姓名,直接返回原字符串
    if (last_space_pos == std::string::npos) {
        return full_name;
    }
    // 截取空格之后的部分作为姓氏
    return full_name.substr(last_space_pos + 1);
}

这种方法效率更高,无需额外的流对象,同时也能处理单字姓名的边界情况。如果姓名末尾存在多余空格,可以先调用trim逻辑去除首尾空格后再执行上述操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 20:12:03