如何从 char* 中删除换行符?

3

我有一个变量:char * tmp,并对其进行了几个操作。最终,我得到了这样的字符串"fffff",但有时在fffff之前会有"\n"。如何删除它?


3
我认为最好的做法是首先防止它发生。你能展示一些代码,描述一下你是如何得到包含“\n”的字符串的吗? - templatetypedef
6
如果涉及到 C++,请考虑使用 std::string 而不是 char * - Vincenzo Pii
搜索和替换。对于 char *,使用 strchrstrpbrk,对于 std::string,使用 find_first_of。随你选择。 - dirkgently
@whiteangle 你可以始终使用其构造函数将 cstring 转换为 std::string,而使用 std::string::c_str() 将 std::string 转换为 cstring。 - Sebastian Hoffmann
我在使用libXML读取国际化HTML文件时遇到了问题,但我有一个非常快速的C / C ++实现,它产生了显着的性能提升。我会好好研究一下。 - John
4个回答

6
char *tmp = ...;

// the erase-remove idiom for a cstring
*std::remove(tmp, tmp+strlen(tmp), '\n') = '\0'; // removes _all_ new lines.

你需要包含什么内容才能使用 #include - Stefan Collier
1
@Splatmistro #include <algorithm>请参见此处 - bames53
1
在这里赋值 '\0' 的意义是什么? - Kulamani

4
在你的问题中,你正在讨论将这个字符串传递给套接字。当将char*指针传递给像套接字这样会复制它的东西时,代码非常简单。
在这种情况下,您可以这样做:
if (tmp[0] == '\n')
  pass_string(tmp+1); // Passes pointer to after the newline
else
  pass_string(tmp);   // Passes pointer where it is

2
在C语言中:
#include <string.h>
tmp[strcspn(tmp, "\n")] = '\0';

这是一个C++问题,不是C。 - Rishi Dua

1

如果 tmp 是动态分配的,请记得使用 tmp 进行释放:

if (tmp[0] == '\n') {
    tmp1 = &tmp[1];
}
else {
    tmp1 = tmp;
}

// Use tmp1 from now on

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接