2012-06-18 966 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 –