如何从C语言中删除给定字符串中的所有空格和制表符?

什么C函数,如果有的话,从字符串中删除所有前面的空格和制表符?

谢谢。

在C中,字符串由指针标识,例如char *str ,或者可能是数组。 无论哪种方式,我们都可以声明自己的指针,指向字符串的开头:

 char *c = str; 

然后我们可以使指针移过任何类似空格的字符:

 while (isspace(*c)) ++c; 

这会将指针向前移动,直到它没有指向空格,即在任何前导空格或制表符之后。 这使原始字符串保持不变 – 我们刚刚更改了指针c指向的位置。

您将需要此包含来获取isspace

 #include  

或者,如果您乐意定义自己对空白字符的想法,可以只编写一个表达式:

 while ((*c == ' ') || (*c == '\t')) ++c; 
 void trim(const char* src, char* buff, const unsigned int sizeBuff) { if(sizeBuff < 1) return; const char* current = src; unsigned int i = 0; while(current != '\0' && i < sizeBuff-1) { if(*current != ' ' && *current != '\t') buff[i++] = *current; ++current; } buff[i] = '\0'; } 

你只需要给予足够的空间。

修剪白色空间的简单function

 #include  #include  #include  char * trim(char * buff); int main() { char buff[29]; strcpy(buff, " \r\n\t abcde \r\t\n "); char* out = trim(buff); printf(">>>>%s<<<<\n",out); } char * trim(char * buff) { //PRECEDING CHARACTERS int x = 0; while(1==1) { if((*buff == ' ') || (*buff == '\t') || (*buff == '\r') || (*buff == '\n')) { x++; ++buff; } else break; } printf("PRECEDING spaces : %d\n",x); //TRAILING CHARACTERS int y = strlen(buff)-1; while(1==1) { if(buff[y] == ' ' || (buff[y] == '\t') || (buff[y] == '\r') || (buff[y] == '\n')) { y--; } else break; } y = strlen(buff)-y; printf("TRAILING spaces : %d\n",y); buff[strlen(buff)-y+1]='\0'; return buff; } 

您可以设置计数器来计算相应的空格数 ,并相应地将字符移动那么多空格。 复杂性最终达到O(n)

 void removeSpaces(char *str) { // To keep track of non-space character count int count = 0; // Traverse the given string. If current character // is not space, then place it at index 'count++' for (int i = 0; str[i]; i++) if (str[i] != ' ') str[count++] = str[i]; // here count is // incremented str[count] = '\0'; }