Get a Substring of a Char* [Duplicate]
For Example, I Have This Char *Buff = "This Is a Test String"; and Want to Get "Test". How Can I Do That? 0 5 Answers Char Subbuff[5]; Memcpy( Subbuff...
For example, I have this
char *buff = "this is a test string";
and want to get "test". How can I do that?
5 Answers
char subbuff[5];
memcpy( subbuff, &buff[10], 4 );
subbuff[4] = '\0';
Job done :)
Assuming you know the position and the length of the substring:
char *buff = "this is a test string";
printf("%.*s", 4, buff + 10);
You could achieve the same thing by copying the substring to another memory destination, but it's not reasonable since you already have it in memory.
This is a good example of avoiding unnecessary copying by using pointers.
Use char* strncpy(char* dest, char* src, int n) from <cstring>. In your case you will need to use the following code:
char* substr = malloc(4);
strncpy(substr, buff+10, 4);
Full documentation on the strncpy function here.
You can just use strstr() from <string.h>
You can use strstr. Example code here.
Note that the returned result is not null terminated.