【问题标题】:Removing the first token within a char array and keeping the rest in C删除 char 数组中的第一个标记并将其余标记保留在 C 中
【发布时间】:2013-11-24 17:09:52
【问题描述】:

所以如果我在 C 中有以下 char 数组:

"a    b       c" // where "a", "b", and "c" can be char arrays of any length and the
                 // space between them can be of any length

如何删除“a”标记,但将其余的“b c”存储在 char 指针中?

到目前为止,我已经实现了以下不起作用的方法:

char* removeAFromABC(char* a, char* abc) {
    char* abcWithoutA[MAXIMUM_LINE_LENGTH + 1];

    int numberOfCharsInA = strlen(a);

    strcpy(abcWithoutA, (abc + numberOfCharsInA));
    return abcWithoutA;
}

【问题讨论】:

  • 怎么样:char *str_minus_sw = &(your_array+2);?
  • 但问题是“sw”并不总是第一个字符
  • 你能简单地将指针前进到数组中的下一个字符吗?
  • char* abcWithoutA[MAXIMUM_LINE_LENGTH + 1]; 声明了一个 MAXIMUM_LINE_LENGTH + 1 字符指针数组,而不是常规字符数组。删除字符后的*...

标签: c string tokenize strtok arrays


【解决方案1】:

在发帖人阐明了他的需求后编辑的答案:

char* removeAFromABC(char* a, char* abc)
{
  char *t;

  t = strstr(abc, a);   /* Find A string into ABC */
  if (t)                /* Found? */
    for (t+=strlen(a);(*t)==' ';t++);   /* Then advance to the fist non space char */
  return t;   /* Return pointer to BC part of string, or NULL if A couldn't be found */
}    

【讨论】:

    【解决方案2】:

    使用 strtok() 标记您的字符串,包括“sw”标记。在您的循环中使用 strcmp() 来查看令牌是否为 'sw',如果是,则忽略它。

    或者,如果您知道 'sw' 始终是字符串中的前两个字符,只需对从 str+2 开始的字符串进行标记以跳过这些字符。

    【讨论】:

      【解决方案3】:
       #include <stdio.h>
       #include<string.h>
      
      int main()
      
       {  char a[20]="sw   $s2, 0($s3)";
      
          char b[20]; //  char *b=NULL; b=(a+5); Can also be done.
      
          strcpy(b,(a+5));
      
          printf("%s",b);
      
       }
      

      或者上面所说的strtok方法。对于 strtok 见 http://www.cplusplus.com/reference/cstring/strtok/

      【讨论】:

        猜你喜欢
        • 2012-04-12
        • 1970-01-01
        • 2019-03-30
        • 2017-02-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-08
        • 2021-12-31
        相关资源
        最近更新 更多