-5

Could you please provide me some code or solution how to split the below string in C programming

Sample string :

SMABCDEFGHIJK,887276617459,5,552612260849779,552612260840646,552612260843632,552612260843525,552612260846817

Output needed :

552612260849779,552612260840646,552612260843632,552612260843525,552612260846817

Basically for the input string we would need to Ignore first 3 positions and want rest of the string in different variable.
The positions to ignore and delimiter values will get the from the database table label.
So, If someone help me to give the logic that would be very helpful

Alexander
  • 16,091
  • 5
  • 13
  • 29
  • You can use `strchr()` to find successive comma delimiters. You can't use `strtok()` because it will break up the rest of the string, unless you want to put it back together. – Weather Vane May 31 '22 at 18:32
  • I think [`strtok`](https://man7.org/linux/man-pages/man3/strtok.3.html) will send you down the right path. – yano May 31 '22 at 18:32
  • 1
    I’m voting to close this question because it is about elementary material that should be learned by reading a C primer or textbook and working on course assignments rather than by asking on Stack Overflow. – Eric Postpischil May 31 '22 at 18:38
  • 1
    @EricPostpischil same as 99.9999999999999999% questions asked here – 0___________ May 31 '22 at 18:39

1 Answers1

1

In your case, you do not need to split the string. Simply ignore everything before the n-th occurrence of the delimiter.

char *ignoreFisrstN(const char *str, int delim, size_t ignoreCount)
{
    char *result = NULL;
    while(ignoreCount--)
    {
        if((str = strchr(str, delim))) str++;
        else break;
    }
    if(str)
    {
        result = malloc(strlen(str) + 1);
        if(result) strcpy(result, str);
    }
    return result;
}


int main(void)
{
    char *s = "SMABCDEFGHIJK,887276617459,5,552612260849779,552612260840646,552612260843632,552612260843525,552612260846817";

    for(size_t i = 0; i < 10; i++)
    {
        char *r = ignoreFisrstN(s, ',', i);

        printf("%zu: `%s`\n", i, r ? r : "NULL");
        free(r);
    }
}

https://godbolt.org/z/xWe74sY46

0___________
  • 60,014
  • 4
  • 34
  • 74