Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use substring function in c?

Tags:

c

substring

I have a string and I want its sub string from 5th location to last location. Which function should I use?

like image 235
maddy2012 Avatar asked May 10 '12 08:05

maddy2012


3 Answers

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

like image 133
Manas Avatar answered Oct 18 '22 07:10

Manas


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);
like image 6
Eric W. Avatar answered Oct 18 '22 08:10

Eric W.


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.

like image 2
john Avatar answered Oct 18 '22 08:10

john