Search Menu


Recursion with the String Library

page 1 of 3

Strings are prevalent in computer programs. As such, languages often contain built-in functions for handling strings; C is no different. The standard library contains functions for dealing with and manipulating strings (to include this library, you would include the string.h library).

Why bring this up in a recursion tutorial? The manipulation of strings is a perfect testing ground for recursive and iterative techniques, due to their repetitive nature (a sequence of successive characters in memory, terminated by a '\0'). Other data structures are inherently recursive, meaning that the data structure refers to itself, allowing for easy manipulation through recursive algorithms; we'll examine these later.

If you were to actually examine how the C string library is implemented, you would almost definitely find it done with iteration (as the coding and understanding complexity of the functions are similar in both the recursive and iterative versions, a programmer would opt to use iteration as it would require fewer system resources, such as less memory on the call stack). That being said, we will examine how different functions from the string library can be written using both techniques, so you can see how they relate. The best way to get a handle on recursion is to practice it a lot.

We'll start with the most basic of the string functions, the strlen() function, which determines the length of a string passed to it. Intuitively, this function counts how many characters there are before the terminating '\0' character. This approach lends itself to an iterative implementation:

int strlen_i(char *s)
	int count = 0;
	for(; *s!='\0'; s) count;
	return count;

The code starts at the beginning of the string, with a count of 0, and for each character until the '\0' it increments the count by 1, returning the final count.

Let's look at this from a recursive standpoint. We break the string into two parts: the small problem we know how to solve, and the smaller version of the big problem that we will solve recursively. In the case of strlen(), the small problem we know how to solve is a single character; for a single character we add one to the count of the rest of the string. The other problem, the smaller version of the original, is the rest of the string following the character at the beginning of the string.