gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 02:08:16 31 4
gpt4 key购买 nike

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

到目前为止,我只能找到 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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com