In c, is there a standard library function that will allow me to extract a substring from a given string, by specifying the starting index, and ending index of the string. Also the substring is not null terminated within the superstring, i. e, getting a simple pointer to the beginning of the substring will not suffice to extract the substring.
Of course I can write a function to do what I want, I merely want to know If any existing library function will suffice for my purpose.
If you are in C
, I maybe can assume that your string is a char *
.
In this case, if you know the start and end index, you can just memcpy
a part of your string to your substring.
This piece of code, for example, would print "str"
:
int main(int argc, const char *argv[])
{
const char *c = "the string";
char *start = &c[4];
char *end = &c[7];
// Note the + 1 here, to have a null terminated substring
char *substr = (char *)calloc(1, end - start + 1);
memcpy(substr, start, end - start);
printf("%s\n", substr);
return 0;
}
So, given a string c
and two values, 4
and 7
, you can get the substring starting at index 4
and ending at index 7
- 1
(this is a normal semantic for "substringing", but you can easily change this code to include also the end
character).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With