prev up next   top/contents search

comp.lang.c FAQ list · Question 13.3

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

A: Not as such. (One reason it doesn't is that, as mentioned in question 7.2 and section 8, C has no managed string type.)

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 */
or, using the trick from question 13.2,
	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] --see also section 6.)

prev up next   contents search
about this FAQ list   about eskimo   search   feedback   copyright

Hosted by Eskimo North