Home > Mobile >  In C, how do I extract the different parts of a string that are all separated by the \0 null termin
In C, how do I extract the different parts of a string that are all separated by the \0 null termin

Time:11-24

So in the following code, I want to store each section in the corresponding variable. Is there an easier way to do this rather than looping through the entire string char by char and checking if it's equal to \0 or not?

int main()
{
    char *test = "Hello My\0friends\0I love food!";
    
    char *section1; // Hello My
    char *section2; // friends
    char *section3; // I love food!

    return 0;
}

CodePudding user response:

You have a character array containing multiple strings.

section1 = test;
section2 = test   strlen(test)  1;
section3 = section2   strlen(section2)   1;

CodePudding user response:

This works:

const char * test = "Hello My\0friends\0I love food!";
const char * section1 = test;
const char * section2 = strchr(section1, 0)   1;
const char * section3 = strchr(section2, 0)   1;

Also, note that the section variables are just pointers into the test string, so you need to make sure the test string does not get deallocated or something, or you need to make copies of these strings before it does get deallocated.

Don't forget to include string.h at the top of your program.

However, I'd like to add that if you didn't know about the strchr function, it should be trivial to implement it yourself by writing a loop that iterates through the string and looks for a null character and returns the pointer to it.

  • Related