Removing the first token within a char array and keeping the rest in C

我们两清 提交于 2019-12-13 06:23:40

问题


So if I have the following char array in C:

"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

How can I remove the "a" token but store the rest "b c" in an char pointer?

So far I have implemented the following method that doesn't work:

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

    int numberOfCharsInA = strlen(a);

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

回答1:


Edited answer after poster has clarified what he needs:

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:


Use strtok() to tokenize your strings, including the 'sw' token. In your loop use strcmp() to see if the token is 'sw', and if so, ignore it.

Or, if you know that 'sw' is always the first two characters in your string, just tokenize your string starting at str+2 to skip those characters.




回答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);

 }

Or the strtok method stated above. For strtok see http://www.cplusplus.com/reference/cstring/strtok/



来源:https://stackoverflow.com/questions/20177347/removing-the-first-token-within-a-char-array-and-keeping-the-rest-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!