temporary_user_name
temporary_user_name

Reputation: 37058

How can I slice a string in C?

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]?

Upvotes: 8

Views: 16780

Answers (2)

kmkaplan
kmkaplan

Reputation: 18960

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.

Upvotes: 10

fvu
fvu

Reputation: 32953

Use strncmp.Assuming buffer is the variable to test, just

strncmp (buffer,"ADD",3);

Upvotes: 8

Related Questions