问题
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