Interview Questions

Does C have anything like the `substr (extract substring) routine present in other languages?

C Interview Questions and Answers


(Continued from previous question...)

Does C have anything like the `substr (extract substring) routine present in other languages?

Not as such.
To extract a substring of length LEN starting at index POS in a source string, use something like
char dest[LEN+1];
strncpy(dest, &source[POS], LEN);
dest[LEN] = '\0'; /* ensure \0 termination */


char dest[LEN+1] = "";
strncat(dest, &source[POS], LEN);

or, making use of pointer instead of array notation,
strncat(dest, source + POS, LEN);
(The expression source + POS is, by definition, identical to &source[POS]

(Continued on next question...)

Other Interview Questions