Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove the first part of a C String

I'm having a lot of trouble figuring this out. I have a C string, and I want to remove the first part of it. Let's say its: "Food,Amount,Calories". I want to copy out each one of those values, but not the commas. I find the comma, and return the position of the comma to my method. Then I use

strncpy(aLine.field[i], theLine, end);

To copy "theLine" to my array at position "i", with only the first "end" characters (for the first time, "end" would be 4, because that is where the first comma is). But then, because it's in a Loop, I want to remove "Food," from the array, and do the process over again. However, I cannot see how I can remove the first part (or move the array pointer forward?) and keep the rest of it. Any help would be useful!

like image 818
Ethan Mick Avatar asked Nov 21 '25 20:11

Ethan Mick


1 Answers

What you need is to chop off strings with comma as your delimiter.

You need strtok to do this. Here's an example code for you:

int main (int argc, const char * argv[]) {


    char *s = "asdf,1234,qwer";
    char str[15];
    strcpy(str, s);
    printf("\nstr: %s", str);
    char *tok = strtok(str, ",");
    printf("\ntok: %s", tok);
    tok = strtok(NULL, ",");
    printf("\ntok: %s", tok);
    tok = strtok(NULL, ",");
    printf("\ntok: %s", tok);

    return 0;
}

This will give you the following output:

str: asdf,1234,qwer
tok: asdf
tok: 1234
tok: qwer
like image 113
Neilvert Noval Avatar answered Nov 23 '25 12:11

Neilvert Noval



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!