【发布时间】:2010-12-03 15:12:54
【问题描述】:
什么 C 函数(如果有)从字符串中删除所有前面的空格和制表符?
【问题讨论】:
-
我已更改标题以匹配文本。因为在我看来,“preceding”这个词不太可能被错误地添加。
什么 C 函数(如果有)从字符串中删除所有前面的空格和制表符?
【问题讨论】:
在 C 中,字符串由指针标识,例如 char *str,或者可能是数组。无论哪种方式,我们都可以声明我们自己的指向字符串开头的指针:
char *c = str;
然后我们可以让我们的指针越过任何类似空格的字符:
while (isspace(*c))
++c;
这将使指针向前移动,直到它不指向空格,即在任何前导空格或制表符之后。这使原始字符串保持不变 - 我们刚刚更改了指针 c 指向的位置。
你需要这个包含来获得isspace:
#include <ctype.h>
或者,如果您愿意自己定义什么是空白字符,您可以编写一个表达式:
while ((*c == ' ') || (*c == '\t'))
++c;
【讨论】:
一个更简单的修剪空白的函数
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char * trim(char * buff);
int main()
{
char 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;
}
【讨论】:
char 数组修复了 main 中的缓冲区溢出:编译器在编译时为您执行复制。
trimleft吗?
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';
}
你只需要给buff足够的空间。
【讨论】:
trim 改成不那么容易误导的名字。
您可以设置一个计数器来计算相应的空格数,并相应地将字符移动那么多空格。最终的复杂度为 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]; // increment count
str[count] = '\0';
}
【讨论】:
trim_left函数。但你的答案很容易适应。