c++ - 如何从 const char * 类型字符串中删除换行符

标签 c++ string

我想从字符串中删除换行符。

到目前为止,我只能找到remove()函数,但我认为begin()和end()不支持const char *类型的字符串。

#include <iostream>
#include <algorithm>

using namespace std;

int main(){
    const char *a = "\n remove all \n the new line characters \n";
    cout << a << "\n";
    remove(a.begin(),a.end(),"\n");
    cout << a;
}

错误-

ctest.cpp: In function ‘int main()’:
ctest.cpp:9:11: error: request for member ‘begin’ in ‘a’, which is of non-class type ‘const char*’
  remove(a.begin(),a.end(),"\n");
           ^
ctest.cpp:9:21: error: request for member ‘end’ in ‘a’, which is of non-class type ‘const char*’
  remove(a.begin(),a.end(),"\n");

我还在互联网上找到了remove_if函数,但它只支持“isspace”、“isdigit”类型的过滤器。没有“isnewline”,直接“\n”会引发错误。我还发现了一些传统的解决方案,这些解决方案基本上在整个字符串上放置了一个循环,但我避免使用这些原始解决方案,因为我对这种语言非常陌生。

最佳答案

首先,通过将 a 放入数组中使其可写,因为您无法修改 const char* 的内容。然后使用std::beginstd::end非成员函数获取序列的两端:

char a[] = "\n remove all \n the new line characters \n";
cout << a << "\n";
remove(std::begin(a), std::end(a), '\n');
cout << a;

Demo.

注意:不用说,在 C++ 中执行此操作的更好方法是使用 std::string

关于c++ - 如何从 const char * 类型字符串中删除换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47739129/

相关文章:

python - 在字符串中查找子字符串,但仅当整个单词?

java - 在java中从扫描仪输入的字符串大写

c++ - 如何比较两个字符串?

c++ - 循环丢弃来自标准输入、Linux C++ 的虚假变量输入

c++ - 在 Win32 上如何将线程移动到另一个 CPU 核心?

c++ - 如何从文本文件中读取和获取整数之和?

c++ - 从通过指向基类的指针存储的 boost 存档中读取对象如何工作?

c++ - 如何检查是否使用 malloc 或 new 分配了内存

javascript - 将字符串拆分为字符串列表

python - 在 Python 中切换两个字符串的首字母?