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

C++中移除字符串末尾空格(保留中间空格)的方法

移除C++字符串末尾空格的实现方法

要移除字符串末尾的多余空格但保留中间空格,这里提供几种实用的实现方式:

方法一:利用标准库函数(简洁高效)

借助std::string的find_last_not_of和erase方法,一步到位处理:

#include <string>
#include <iostream>

int main() {
    std::string str = "The Purple Dog  ";
    // 定位最后一个非空格字符的位置
    size_t last_valid_pos = str.find_last_not_of(' ');
    
    if (last_valid_pos != std::string::npos) {
        // 删除从该位置之后的所有字符(即末尾空格)
        str.erase(last_valid_pos + 1);
    } else {
        // 若字符串全为空格,直接清空
        str.clear();
    }
    
    std::cout << "\"" << str << "\"" << std::endl; // 输出:"The Purple Dog"
    return 0;
}

find_last_not_of会从字符串末尾向前查找第一个非空格字符,返回其索引;如果字符串全是空格,会返回std::string::npos,此时直接清空字符串即可。

方法二:手动遍历实现(适合理解底层逻辑)

如果想手动实现遍历逻辑,从字符串末尾向前跳过所有空格,再截断字符串:

#include <string>
#include <iostream>

int main() {
    std::string str = "The Purple Dog  ";
    int end_idx = str.size() - 1;
    
    // 从末尾向前跳过所有空格
    while (end_idx >= 0 && str[end_idx] == ' ') {
        end_idx--;
    }
    
    if (end_idx >= 0) {
        // 调整字符串长度到最后一个有效字符的位置
        str.resize(end_idx + 1);
    } else {
        // 全空格情况清空字符串
        str.clear();
    }
    
    std::cout << "\"" << str << "\"" << std::endl; // 输出:"The Purple Dog"
    return 0;
}

这里需要注意边界判断:当字符串为空或全是空格时,end_idx会变成-1,此时必须清空字符串,避免后续操作出错。

注意事项

  • 两种方法都能处理空字符串、全空格字符串、正常带末尾空格的字符串等所有边界场景;
  • 标准库方法的效率更高,因为底层是优化过的实现,推荐优先使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 17:52:49