Get a substring of a char*
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>
Related videos on Youtube
J0e3gan
Results-oriented software professional with strong multi-industry, multi-platform, multi-language, multi-discipline experience – as a manager, lead, developer, administrator, help-desk technician, and lifelong digital explorer. Particularly enjoy working with high-performance people & technology in dynamic Agile teams and mentoring. Recently managing technical aspects of customers' Adobe Campaign implementations to drive their digital marketing success. Find me on LinkedIn: https://linkedin.com/in/J0e3gan
Updated on July 14, 2020Comments
-
J0e3gan almost 4 years
For example, I have this
char *buff = "this is a test string";
and want to get
"test"
. How can I do that? -
evandrix over 11 yearsdon't forget to add the null-termination character '\0' if you do this.
-
Grault over 10 yearsThis is kind of the reverse of a normal substring operation - more like indexOf.
-
alexandernst over 10 yearsThis will waste memory. You have been warned! :P
-
Goz over 10 years@alexandernst: How exactly? 5 bytes allocated on the stack (which will get freed when it drops out of scope) is hardly wasting memory ...
-
alexandernst over 10 yearsStill more than what you need, but yeah, they'll get free-ed as soon as the code leaves the current stack.
-
Goz over 10 years@alexandernst: The problem is that you can't do much with that string data without copying it. If you take a pointer to the section from the original string you need to know the length as it will have no null terminator (Without affecting the original string).
-
Juan Pablo Rinaldi over 10 yearsDon't forget to #include <string.h>.
-
FUD over 8 yearsdon't forget to malloc the substr large enough if you do this.
-
Blagovest Buyukliev over 8 years@procrastinator: Not really only for printing. This is a viable approach in case the substring is not going to be modified. This way you simply keep a pair of pointers instead of allocating a variable-length buffer.
-
Admin over 8 yearsN̶i̶c̶e̶ ̶o̶n̶e̶ ̶f̶o̶r̶ ̶p̶r̶i̶n̶t̶i̶n̶g̶ ̶o̶n̶l̶̶̶̶y̶ Sorry if you got me wrong, I mean that your solution doesn't require an extra string, which is perfect when you only need to print :-)
-
Parnab Sanyal over 7 yearsuse sprintf to store the above formatted string
-
adrian over 6 yearsSee Grault's comment down below
-
Verma Aman over 5 years@ParnabSanyal how can I use sprintf to store the substring? Do I need to pass substring length as third parameter?
-
Parnab Sanyal over 5 years@VermaAman no you don't. Your first argument would be the resulting string, second argument would be the source string and if you have placeholders inside second argument like
%c
,%i
etc then from third argument to upto the number of placeholders, would be the actual values of the placeholder( comma separated). Just likeprintf
-
TNT almost 4 years@Juampi: Is string.h really needed? You're only using arrays and memcpy.
-
TNT almost 4 years@alexandernst: Couldn't you reuse the same buff?
memcpy(buff, &buff[10], 4);
buff[4] = '\0';
-
Ekrem Dinçel over 3 years@TNT writing to pointer to string literal is undefined behavior. Your code crashes the program on my machine. See this.
-
Good man over 3 yearssubbuff[4] = '\0'; this is very important, thanks for answer.
-
VimNing about 3 years@Barmar: So in your definition what is substring?
-
Barmar about 3 years@Rainning A substring is any contiguous portion of a string. E.g.
def
is a substring ofabcdefghi
-
VimNing about 3 years@Barmar: Then since
strstr()
return the first index of the substring it found, but you said it's not just the substring. -
Barmar about 3 yearsThe question asked how to get
test
fromthis is a test string
. This answer would returntest string
, not justtest
. -
Barmar about 3 yearsYes it is a substring, but it's limited to substrings that reach the end, it doesn't work if you want shorter substrings as in the question.