如何从const char *类型字符串中删除新线字符

How to remove the new-line characters from const char * type string

本文关键字:字符串 删除 新线 字符 类型 const char      更新时间:2023-10-16

我想从字符串中删除新系列字符。

到目前为止
#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");

我还在Internet上找到了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;

演示。

注意:不用说在C 中这样做的更好方法是使用std::string