How can I slice a string in C?

temporary_user_name picture temporary_user_name · Dec 2, 2012 · Viewed 13.3k times · Source

I need to find if a char array starts with "ADD". I know to use strcmp(), but I don't know how to get the first three characters. I really hate working with c-strings. How can I take a slice of a char array like char buffer[1024]?

Answer

kmkaplan picture kmkaplan · Dec 2, 2012

Use strncmp("ADD", buffer, 3).

I am not sure what you mean by “slice” but any pointer inside buffer could be considered a slice. For example if buffer is a string that starts with "ADD" then char *slice = buffer + 3 is the same string with "ADD" removed. Note that slice is then a part of buffer and modifying the content of the slice will modify the content of the buffer. And the other way round.

If by “slice” you mean an independant copy then you have to allocate a new memory block and copy the interesting parts from buffer to your memory. The library functions strdup and strndup are handy for this.