【c++】C++字符串删除末尾字符的三种实现方法

在C++开发中,经常需要处理字符串末尾字符的删除操作。本文将详细介绍三种常用的实现方法,并提供完整的代码示例和对比分析。

方法对比与实现

使用pop_back()方法

pop_back()是C++11标准引入的方法,可以直接删除字符串的最后一个字符。这种方法简洁高效,但需要确保字符串不为空。

c 复制代码
#include <iostream>
#include <string>

using namespace std;

int main() {
    string str = "Hello World!";
    
    if (!str.empty()) {
        str.pop_back();
        cout << "Method 1: " << str << endl;
    }
    
    return 0;
}

使用erase()方法

erase()方法通过迭代器定位要删除的位置,可以更灵活地控制删除操作。需要特别注意迭代器的有效性检查。

c 复制代码
#include <iostream>
#include <string>

using namespace std;

int main() {
    string str = "Hello World!";
    
    if (!str.empty()) {
        str.erase(str.end() - 1);
        cout << "Method 2: " << str << endl;
    }
    
    return 0;
}
使用substr()方法

substr()方法通过截取子串来实现删除末尾字符的效果。这种方法需要计算新的子串长度,适用于需要保留部分字符串的场景。

c 复制代码
#include <iostream>
#include <string>

using namespace std;

int main() {
    string str = "Hello World!";
    
    if (!str.empty()) {
        str = str.substr(0, str.length() - 1);
        cout << "Method 3: " << str << endl;
    }
    
    return 0;
}
方法对比分析
方法 适用版本 性能 安全性 灵活性
pop_back() C++11+
erase() 所有版本
substr() 所有版本
参考
相关推荐
lang2015092819 小时前
Apache POI Word(docx) 实战教程:从入门到精通表格合并、图片插入与文档合并
java·开发语言·word
小牛不牛的程序员19 小时前
利用Claude Code构建自动化需求挖掘工具:从原理到实践
java·算法·自动化
Robot_Nav19 小时前
C++ 面试常问问题汇总:基础语法、面向对象、STL、多线程与设计模式
c++·设计模式·面试
wear工程师19 小时前
腾讯天美一面:从 HashMap 到 Spring 事务,面试官这套连环问到底在考什么
java·面试
盐焗鹌鹑蛋19 小时前
【C++】二叉搜索树
c++
哎呦,帅小伙哦20 小时前
C++工程实战: 预处理宏、宏重定义避坑、LOG_TAG业务实践与__COUNTER__深度解析
c++
鱼毓屿御20 小时前
Python 装饰器与函数调用机制(复习笔记 · 2026-07-07)
开发语言·python
浩瀚地学20 小时前
【Java基础复习】IO流(二)
java·开发语言·经验分享·笔记·学习
hdsoft_huge20 小时前
SpringBoot系列06:RESTful接口开发,请求参数接收、全局跨域CORS完整配置
java·spring boot
IVVi0jToe20 小时前
高效C++线程池设计与实现
java·c++·安全