在 C++ 中,可以使用 erase() 函数和 find() 函数去除字符串中的换行符。
以下是代码示例:
#include <iostream>
#include <string>
int main() {
std::string str = "This is a\nstring with\nnewlines.";
std::cout << "Before: " << str << std::endl;
std::string::size_type pos = 0;
while ((pos = str.find("\n", pos)) != std::string::npos) {
str.erase(pos, 1);
std::cout << "After: " << str << std::endl;
return 0;
代码中,我们首先声明了一个字符串 str
,其中包含了换行符。然后,使用 find() 函数在字符串中查找换行符,并使用 erase() 函数删除它。该过程需要重复多次,直到所有换行符都被删除为止。