Get a substring of a char*

CCharSubstring

C Problem Overview


For example, I have this

char *buff = "this is a test string";

and want to get "test". How can I do that?

C Solutions


Solution 1 - C

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

Job done :)

Solution 2 - C

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 - C

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 - C

You can use strstr. Example code here.

Note that the returned result is not null terminated.

Solution 5 - C

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

$ man strstr

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser502230View Question on Stackoverflow
Solution 1 - CGozView Answer on Stackoverflow
Solution 2 - CBlagovest BuyuklievView Answer on Stackoverflow
Solution 3 - CMihai ScurtuView Answer on Stackoverflow
Solution 4 - CMilanView Answer on Stackoverflow
Solution 5 - CPaul RView Answer on Stackoverflow