我有一个变量:char * tmp
,并对其进行了几个操作。最终,我得到了这样的字符串"fffff"
,但有时在fffff之前会有"\n"
。如何删除它?
char *tmp = ...;
// the erase-remove idiom for a cstring
*std::remove(tmp, tmp+strlen(tmp), '\n') = '\0'; // removes _all_ new lines.
#include
? - Stefan Collierif (tmp[0] == '\n')
pass_string(tmp+1); // Passes pointer to after the newline
else
pass_string(tmp); // Passes pointer where it is
#include <string.h>
tmp[strcspn(tmp, "\n")] = '\0';
如果 tmp 是动态分配的,请记得使用 tmp
进行释放:
if (tmp[0] == '\n') {
tmp1 = &tmp[1];
}
else {
tmp1 = tmp;
}
// Use tmp1 from now on
C++
,请考虑使用std::string
而不是char *
。 - Vincenzo Piichar *
,使用strchr
、strpbrk
,对于std::string
,使用find_first_of
。随你选择。 - dirkgently