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

时间:2012-06-18 19:36:46

标签: c++ string newline

我有一个变量:char * tmp,我用它做了一些操作。最后,我有类似"fffff"的内容,但有时候在fffff "\n"之前。我该如何删除它?

4 个答案:

答案 0 :(得分:6)

char *tmp = ...;

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

答案 1 :(得分:4)

在您的问题中,您正在谈论将此字符串传递给套接字。将char *指针传递给类似socket的东西时会复制它,这样做的代码非常简单。

在这种情况下,您可以这样做:

if (tmp[0] == '\n')
  pass_string(tmp+1); // Passes pointer to after the newline
else
  pass_string(tmp);   // Passes pointer where it is

答案 2 :(得分:2)

在C:

#include <string.h>
tmp[strcspn(tmp, "\n")] = '\0';

答案 3 :(得分:1)

如果动态分配tmp,请记住使用tmp释放它:

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

// Use tmp1 from now on