2012-06-18 959 views
3

我有一个变量:char * tmp,我做了几个操作。最后,我有这样的"fffff",但有时在fffff之前是"\n"。我如何删除它?如何从char *中删除换行符?

+3

我认为最好的行动方针是防止它摆在首位到达那里。你能告诉我们一些描述你如何结束包含'\ n'的字符串的代码吗? – templatetypedef

+6

如果是'C++',请考虑使用'std :: string'而不是'char *' –

+0

搜索并替换。 'strchr','strpbrk'代表'char *','find_first_of'代表'std :: string'。拿你的选择。 – dirkgently

回答

6
char *tmp = ...; 

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

你需要为此包括什么? – Splatmistro

+1

@Splatmistro'#include '。 [见这里](http://en.cppreference.com/w/cpp/algorithm/remove) – bames53

1

如果tmp目录是动态分配记住释放它使用tmp

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

// Use tmp1 from now on 
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'; 
+0

这是一个C++的问题,而不是C –