Get a substring of a char* [duplicate]

2019-01-03 12:41发布

This question already has an answer here:

For example, I have this

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

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

标签: c char substring
5条回答
Emotional °昔
2楼-- · 2019-01-03 12:58

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.

查看更多
在下西门庆
3楼-- · 2019-01-03 12:58

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.

查看更多
我命由我不由天
4楼-- · 2019-01-03 13:02

You can use strstr. Example code here

Note that the returned result is not null terminated.

查看更多
等我变得足够好
5楼-- · 2019-01-03 13:11
char subbuff[5];
memcpy( subbuff, &buff[10], 4 );
subbuff[4] = '\0';

Job done :)

查看更多
对你真心纯属浪费
6楼-- · 2019-01-03 13:12

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

$ man strstr

查看更多
登录 后发表回答