Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Library function to extract substring by position index

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.

like image 583
Ajoy Avatar asked Oct 15 '14 07:10

Ajoy


1 Answers

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).

like image 176
Vincenzo Pii Avatar answered Sep 28 '22 03:09

Vincenzo Pii