Book
Collection
Click for Table of Contents
© 2025 by Rance D. Necaise
C Primer for Python Programmers
Copyright © 2025
Rance D. Necaise

8.4 String Functions

string.h

As indicated earlier, C includes a collection of functions in its standard library for working with strings. The functions are defined in the <string.h> module. We will explore some of these functions in this and the following sections.

The length of a string is indicated by the number of characters that it contains. This value can be computed using the strlen function.

Prototype
The String Length Function
string.h
int strlen(char str[]);
The function takes a string as an argument and returns as an integer the number of characters that it contains.

Consider the following declarations

  1. char message[] = "Hello, World";
  2. int size;

then the function call

  1. size = strlen(message);

will return 12, the number of characters in the string "Hello, World". As indicated earlier the null character is not included in the size since it is not a character in the string. It is only used to indicate the end of the string.

Worked Example
Printing in Reverse

The strlen function is commonly used when iterating over the elements of the string. Instead of having to check for the null character, you can compute the length of the string and use that value as part of a count-controlled loop. For example, consider the fruit array from the previous section,

Suppose we want to print the string in reverse order, all on one line. This can not be done with the printf function. Instead, we must write our own loop to iterate over the string, starting at the end and working backwards:

  1. int i = strlen(fruit) - 1;
  2. while(i >= 0) {
  3.   printf("%c", fruit[i]);
  4.   i++;
  5. }
  6. printf("\n");
Special Topic
Segmentation Faults


Question 8.4.1

Consider the following array declarations:

  1. char name[35] = "John Smith";
  2. char text[50] = "";

Indicate what is returned by each of the given function calls.

Statement Result Explanation
size = strlen(name); 10 name contains the string "John Smith" which contains 10 characters.
size = strlen(text); 0 The string array contains the empty string, which contains no characters.
Question 8.4.2

Consider the following array declarations:

  1. char memo[35];

What is the result of executing the following statement?

  1. int len = strlen(memo);

The results are unpredictable since the memo character array was not initialized with a string.

Question 8.4.3

Suppose the C standard library did not provide the strlen function. Design and implement your own version of the function which works identical to the original.

  1. int strlen(char str[])
  2. {
  3.   int i = 0;
  4.   while(str[i] != 0) {
  5.     i++;
  6.   }
  7.   return i;
  8. }