C - 删除字符串中特定字符周围的空格

C - Delete spaces around specific char in string

我有一个 80 个字符的字符串(来自 .txt 文件的行)
在字符串末尾的某处,我在它们之间有数字或字符串或字符和“,”(逗号)。
我需要删除“,”周围的这些空格,这样我就能在 strtok() 之前得到它们。
有任何想法吗 ?
例如:

String : " name: today 12 ,r ,ab,     5     ,   seven"<br>

我需要:" name: today 12,r,ab,5,seven"

你可以试试这个!
必要时替换为您的代码。

#include <stdio.h>
#include <stdlib.h>

int main()
{   int i;
    char line[] = "name: today 12 ,r ,ab, 5 , seven";
    int length = strlen(line);
    char line2[length];
    for(i = 0; i<length; i++) {
        if(!isspace(line[i])) {
             line2[i] = line[i];
        }
    }
    for(i = 0; i<length; i++){
        printf("%c", line2[i]);
    }
    return 0;
}

你可以应用这个算法::

  1. 查找元素 ,在本例中为 space.
  2. 用您选择的元素替换该元素,在本例中为空字符。

此函数可能会方便地用于将任何字符替换为字符串。您可以将 char *replace 函数添加为代码片段,稍后将其用于类似目的。

   char *replace(const char *the_input_string, char the_character,
                 const char *replacing_string) 
  {
      int count = 0;
      const char *t;
      for(t=the_input_string; *t; t++)
          count += (*t == the_character);

      size_t rlen = strlen(replacing_string);
      char *res = (char*)malloc(strlen(the_input_string) + (rlen-1)*count + 1);
      char *ptr = res;
      for(t=the_input_string; *t; t++) 
      {
          if(*t == the_character) 
          {
              memcpy(ptr, replacing_string, rlen);
              ptr += rlen;
          }
          else 
              *ptr++ = *t;
      }
      *ptr = 0;
      return res;
  }

驱动程序::

int main(int argc, char const *argv[])
{
    const char *s = replace("name: today 12 ,r ,ab, 5 , seven", ' ', "");
    printf("%s\n", s);
    return 0;
}

请参考this link ,代码可能非常相似,但使用上面的代码作为解决方案可能会抛出一些错误或警告。

因为生成的字符串会比原来的字符串短,所以可以原地替换:找到逗号后复制,跳过下面的space。要处理逗号前的 space,请跟踪最后一个非 space 字符之后的第一个 space 并在必要时跳过它:

    #include <stdlib.h>
    #include <stdio.h>
    #include <ctype.h>

    void remspc(char *str)
    {
        char *first = str;          // dest. char after last non-space
        char *q = str;              // destination pointer

        // skip leading white space
        while (isspace((unsigned char) *str)) str++;

        while (*str) {
            if (*str == ',') {
                q = first;          // skip space before comma
                *q++ = *str++;
                first = q;

                // skip space after comma
                while (isspace((unsigned char) *str)) str++;
            } else {
                // remember last non-space
                if (!isspace((unsigned char) *str)) first = q + 1;
                *q++ = *str++;
            }
        }

        *first = '[=10=]';
    }

    int main(void)
    {
        char str[] = " name: today 12, r ,ab,   ,   5     ,   seven";

        remspc(str);
        puts(str);

        return 0;
   }

此解决方案将 运行 由白色 space 分隔的逗号放在一起,这可能会导致 strtok 出现问题,因为它将逗号的延伸视为单个分隔符。