什么 C 函数(如果有)从字符串中删除所有前面的空格和制表符?
问问题
19524 次
4 回答
15
在 C 中,字符串由指针标识,例如char *str
,或者可能是数组。无论哪种方式,我们都可以声明我们自己的指向字符串开头的指针:
char *c = str;
然后我们可以让我们的指针越过任何类似空格的字符:
while (isspace(*c))
++c;
这将使指针向前移动,直到它不指向空格,即在任何前导空格或制表符之后。这使原始字符串保持不变-我们刚刚更改了指针c
指向的位置。
您将需要这个包括来获得isspace
:
#include <ctype.h>
或者,如果您乐于定义自己的空白字符是什么,您可以编写一个表达式:
while ((*c == ' ') || (*c == '\t'))
++c;
于 2009-10-03T19:50:42.883 回答
1
修剪空白的更简单功能
#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;
}
于 2017-11-14T17:40:12.250 回答
0
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足够的空间。
于 2009-10-03T20:20:30.623 回答
0
您可以设置一个计数器来计算相应的空格数,并相应地将字符移动那么多空格。复杂性最终达到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';
}
于 2018-01-27T05:41:58.487 回答