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]?
In C, the strtok() function is used to split a string into a series of tokens based on a particular delimiter. A token is a substring extracted from the original string.
lets we take input from user and if string length is greater than 10 we slice first 5 string and print out next 5 string to the console. We will need to function that we custom create without string functions that available in c library. One is string length checker and 2nd is to slice string.
The slice() method extracts a part of a string. The slice() method returns the extracted part in a new string. The slice() method does not change the original string. The start and end parameters specifies the part of the string to extract.
Slicing StringsYou can return a range of characters by using the slice syntax. Specify the start index and the end index, separated by a colon, to return a part of the string.
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.
Use strncmp.Assuming buffer is the variable to test, just
strncmp (buffer,"ADD",3);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With