Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 259
temporary_user_name Avatar asked Dec 02 '12 22:12

temporary_user_name


People also ask

How do you slice a string in C?

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.

Can we slice Strings in C?

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.

How do you slice a 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.

Is Slicing allowed in string?

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.


2 Answers

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.

like image 85
kmkaplan Avatar answered Oct 30 '22 21:10

kmkaplan


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

strncmp (buffer,"ADD",3);
like image 8
fvu Avatar answered Oct 30 '22 21:10

fvu