删除空格和制表符的函数

问题描述:

即时尝试创建一个函数,该函数从给定字符串中除去字符串中的第一个制表符或空格以外的空格和制表符。当即时通讯使用我的功能时,它会删除第一个空格和制表符,但它也会删除第一个空格或制表符后的第一个字母。 例如>“ad ad ad”>“ad adad”instead of“ad adad” 这是为什么?删除空格和制表符的函数

void RemoveSpacetab(char* source) { 
    char* i = source; 
    char* j = source; 
    int spcflg = 0; 

    while(*j != 0) { 
     *i = *j++; 

     if((*i != ' ') && (*i != '\t')) 
      i++; 
     if(((*i == ' ') || (*i == '\t')) && (spcflg == 0)) { 
      i++; 
      spcflg = 1; 
     } 
    } 
    *i = 0; 
} 
+1

尝试坐下来一张纸,并通过觉得这。你说如果第一个字符是空格或制表符,它应该保留?然后检查* first *,如果是这样,就跳过它。然后进入复制循环。在循环中,只需从'source'复制到'dest'(在循环之前初始化为指向'source'),除非'* source'是一个空格或标签,在这种情况下,你什么也不做。增加'source'和'dest'指向复制的下一个位置。迭代直到'* source'是字符串终止符。结束循环并将终止符添加到'dest'。完成! –

+0

也许您长时间使用了Pascal/Delphi。在C中,不需要像'if(* i!=''&& * i!='\ t')'那样使用括号。 – i486

+0

变量名称应该指明“content”或“usage”。变量'我'是毫无意义的,即使在当前的情况下 – user3629249

您将需要将源数组和目标数组分开,因为它们会变成不同的长度。您可以在复制此类字符之前找到起始位置,假设您将源和源的长度作为char* source, int length(您也可以使用strlen(source)计算源的长度,那么您的函数可能如下所示:

int i = 0; 
char* dest = malloc(sizeof(char) * length); 
// Increment i until not space to find starting point. 
while (i < length && (source[i] == '\t' || source[i] == ' ')) i++; 

int dest_size = 0; 
while (i < length) { 
    if (source[i] != '\t' && source[i] != ' ') { 
     // Copy character if not space to dest array 
     dest[dest_size++] = source[i]; 
    } 
    i++; 
} 
dest[dest_size++] = 0; // null terminator 
// Feel free to realloc to the right length with 
// realloc(dest, dest_size * sizeof(char)) 
return dest; 

造成两个if报表一前一后的问题你i当你发现了首次空间先j

说明:

在第一个循环中,i也指向位置0和j。位置0处的'a'将被自身覆盖,然后j向前移动至位置1。您的第一if块找出在位置0的字符不是空格,而不是一个选项卡,所以移动i到位置1

在第二次循环的'b'将与本身被覆盖然后j移动到位置2,其是一个空间。第一个if发现位置1处的'b'不是空格,也不是标签,因此将i移动到位置2.现在第二个if发现i第一次指向空间并将其移动到位置3 j是仍然指向位置2

在3次循环的'a'在位置3将与在位置2 j赶上i的空间和被覆盖。

一个可能的修复你的代码:

#include <stdio.h> 

void RemoveSpacetab(char* source) { 
    char* i = source; 
    char* j = source; 
    char spcflg = 0; 

    while(*j != 0) { 
     *i = *j++; 
     if(*i == ' ' || *i == '\t') { 
      if(!spcflg) { 
       i++; 
       spcflg = 1; 
      } 
     } 
     else { 
      i++; 
     } 
    } 
    *i = 0; 
} 

int main() { 
    char my_string[] = "ad ad ad"; 
    RemoveSpacetab(my_string); 

    printf("%s\n", my_string); 
    return 0; 
} 
+0

“j'仍然指向第一个'ab'后面的空间,但'i'指向'a''” - 'j'增加了'* j ++',所以它也指向'a'。 – SHG

+0

我的不好。为你+1,这正是问题所在。 – SHG

+0

我扩大了我的解释,因为前一个有点模糊。 – Akira