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, &buff[10], 4 );
subbuff[4] = '\0';

Job done :)

9

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.

5

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.

2

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

$ man strstr

6

You can use strstr. Example code here.

Note that the returned result is not null terminated.

1

You Might Also Like