Thomas Jeffrey Thomas Jeffrey - 18 days ago 6
C Question

C string separation

I looked at related topics, tried some of the examples and didn't found anything that helps me.

I am taking a string for input eg char str[50]
it has the following format Remove 1 1
Remove can be another word which has different length
the number of integers could be more than 2
I need each part of the string to be stored in different variables for the numeric values int if possible

I tried with strcmp stracat strtok strstr but apparently I am missing something

char str[] = "Remove 2 3 2";
char * pch;
char split[50];
printf("Splitting string \"%s\" into tokens:\n", str);
pch = strtok(str, " ");
while (pch != NULL) {
printf("%s\n", pch);
strcat(split,pch);
printf("\nThe string is %s",split);
pch = strtok(NULL, " ");
}


This is my latest attempt. What I'm trying to do is to remove the space characters, then probably I could identify the word behind Remove e.g. if it is remove or it is some other word with strstr. But How to get the numeric values separated? And this is my output how to get rid of these characters

The string is ��_o�Remove2

The string is ��_o�Remove23

The string is ��_o�Remove232

The string is ��_o�Remove232

Answer

As i understand you may be wanted each string component into a separate variable, then why not using an array instead ??

just check for space and ignore them

  char str[] = "hi 1 2 3";
    char store[100];
    int i=0,j=0;

    for(i = 0,j = 0; i <= strlen(str); i++){
        if(str[i] != 32) {   // value of space is 32
                store[j] = str[i];
                j++;
        }
    }

    for( i = 0; i < strlen(store); i++){
        printf("%c\n",store[i]);
    }

output :

h
i
1
2
3