如何从const char * type字符串中删除换行符

时间:2017-12-10 13:04:06

标签: 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函数,但它只支持&#34; isspace&#34;,&#34; isdigit&#34;过滤器类型。没有&#34; isnewline&#34;直接&#34; \ n&#34;扔错了。我还发现了一些传统的解决方案,这些解决方案基本上会对整个字符串进行循环,但我正在避免使用这些原始解决方案,因为我对这种语言并不熟悉。

1 个答案:

答案 0 :(得分:2)

首先,通过将a置于数组中使const char*可写,因为您无法修改std::begin的内容。然后使用std::endchar a[] = "\n remove all \n the new line characters \n"; cout << a << "\n"; remove(std::begin(a), std::end(a), '\n'); cout << a; 非成员函数来获取序列的两端:

std::string

Demo.

注意:不言而喻,在C ++中使用toString更好的方法是使用System.out.println(Arrays.deepToString(newArray));

相关问题