我想从字符串中删除换行符。
到目前为止,我只能找到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::begin
和std::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
。
关于c++ - 如何从 const char * 类型字符串中删除换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47739129/