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?


Solution 1:

char subbuff[5];
memcpy( subbuff, &buff[10], 4 );
subbuff[4] = '\0';

Job done :)

Solution 2:

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.

Solution 3:

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.

Solution 4:

You can use strstr. Example code here.

Note that the returned result is not null terminated.

Solution 5:

You can just use strstr() from <string.h>

$ man strstr