C++ 如何去掉 string 类型中的换行符 (\n)?

关注者
1
被浏览
3,229

1 个回答

若换行符存在与中间

#include <string>
std::string str = "Hello, world!\n";
// 查找换行符的位置
size_t pos = str.find('\n');
// 如果找到了换行符
if (pos != std::string::npos) {
  // 在换行符的位置删除一个字符,即删除换行符
  str.erase(pos, 1);
// 输出 "Hello, world!"
std::cout << str << std::endl;

去除两端空格

#include <iostream>
#include <string>
// 去掉字符串两端的空格
void strip(std::string &s) {
    // 去掉字符串开头的空格
    s.erase(0, s.find_first_not_of(" "));
    // 去掉字符串末尾的空格
    s.erase(s.find_last_not_of(" ") + 1);
int main() {
    std::string s = "   Hello, world!   ";
    std::cout << "Before strip: " << s << '\n';