Lesson 2 of 6 · Strings, Structs and Files · 3 min read · Updated

Writing your own string functions: reverse, length, palindrome

How the library functions work inside — by writing length, reverse and palindrome checks yourself.

A string is a char array ending in \0. Every string function is just a loop that walks the characters until it meets that \0. Writing a few yourself is the best way to understand strings — and a favourite interview question.

c
#include <stdio.h>

int my_strlen(const char s[])
{
    int n = 0;
    while (s[n] != '\0') {
        n++;
    }
    return n;
}

void reverse(char s[])
{
    int i = 0, j = my_strlen(s) - 1;
    while (i < j) {                 /* swap the ends, move inwards */
        char t = s[i];
        s[i] = s[j];
        s[j] = t;
        i++;
        j--;
    }
}

int is_palindrome(const char s[])
{
    int i = 0, j = my_strlen(s) - 1;
    while (i < j) {
        if (s[i] != s[j]) {
            return 0;
        }
        i++;
        j--;
    }
    return 1;
}

int main(void)
{
    char word[] = "Madurai";

    printf("length: %d\n", my_strlen(word));
    reverse(word);
    printf("reversed: %s\n", word);
    printf("malayalam: %s\n", is_palindrome("malayalam") ? "palindrome" : "not a palindrome");
    printf("chennai: %s\n", is_palindrome("chennai") ? "palindrome" : "not a palindrome");
    return 0;
}
Output
length: 7
reversed: iarudaM
malayalam: palindrome
chennai: not a palindrome
  • Length: count characters until \0. This is exactly what strlen does.
  • Reverse: two positions, i from the front and j from the back. Swap them and step inwards until they meet. Only half the string is walked.
  • Palindrome: the same two positions, but compare instead of swap. The first mismatch means "not a palindrome".

Warning

reverse changes the array it is given, so it needs a real array like char word[] = "Madurai";. Passing a string literal directly — reverse("Madurai") — tries to change read-only memory and usually crashes. Also note that strrev, found in some old compilers, is not standard C.

In reverse, why does the loop stop when i < j becomes false?

Try this now

  1. Write count_vowels(const char s[]) and test it on your name.
  2. Write to_upper(char s[]) that turns lowercase letters into capitals (hint: 'a' to 'z', subtract 32).
  3. Make is_palindrome ignore capital letters, so "Madam" counts as a palindrome.
  4. Write my_strcpy(char dest[], const char src[]) and remember to copy the \0 too.

Create a free account to save your progress, or sign in.