How to use substring function in c?
If you won't be using the original string for anything else, you can just use &s[4]
directly. If you need a copy, do
char new_str[STR_SIZE + 1] = {0};
strncpy(new_str, &s[4], STR_SIZE);
You can use the memcpy()
function which is in string.h
header file.
memcpy()
copies bytes of data between memory blocks, sometimes called buffers. This function doesn't care about the type of data being copied--it simply makes an exact byte-for-byte copy. The function prototype is
void *memcpy(void *dest, void *src, size_t count);
The arguments dest and src point to the destination and source memory blocks, respectively. count specifies the number of bytes to be copied. The return value is dest.
If the two blocks of memory overlap, the function might not operate properly -- some of the data in src might be overwritten before being copied. Use the memmove()
function, discussed next, to handle overlapping memory blocks. memcpy()
will be demonstrated in program below.
You can also find an example for these function over here: http://www.java-samples.com/showtutorial.php?tutorialid=591
If you know the character also in the string from where you want to get the substring then you can use strstr function. It locates the substring. But if u do not know the character from where you want to retrieve then you can use the strcpy or strncpy to get the string as Eric has mentioned.