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]?
Asked
Active
Viewed 1.6k times
8

temporary_user_name
- 35,956
- 47
- 141
- 220
2 Answers
10
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.

kmkaplan
- 18,655
- 4
- 51
- 65
-
How could one specify an offset and an end that is shorter than the original char sequence? Like "hello" + 1 size 3 (so "ell"); That's what is meant by slice I believe. Luckily strncmp and printf offer options to work with this, but it would be neat to show this as a char sequence – scape Oct 22 '17 at 15:15
-
@scape See [How to extract a substring from a string in C?](https://stackoverflow.com/questions/19555434) – kmkaplan Oct 23 '17 at 10:25
-
"strtok typically replaces delimiters with '\0' as it "eats" the input." which obviously has some drawbacks. – scape Oct 23 '17 at 14:41
-
@scape Yes. If you really have a question you should ask it as such. – kmkaplan Oct 24 '17 at 18:09