Reading history

Writing Your Own String Functions in C

7 min read 0 views

Rebuild strlen, strcpy, strcat and strcmp in C with pointers, then write reverse, palindrome check, trim and word count functions.

The functions in <string.h>, such as strlen and strcpy, look like magic until you write them yourself. Then you see that a C string is just characters in a row, ending with a '\0' byte, and every string function is a short loop that walks along them. Writing your own versions is a classic exam and interview exercise, and the best way to understand pointers. This lesson rebuilds four library functions, then writes reverse, palindrome, trim and word-count functions.

In this lesson you will learn

  • How strlen, strcpy, strcat and strcmp work inside
  • Walking a string with pointers
  • Reversing a string in place
  • Checking palindromes while ignoring case and punctuation
  • Trimming spaces and counting words

You should know strings, string functions and pointer arithmetic.

Rebuilding the Library Functions

#include <stdio.h>
#include <stddef.h>

/* Our own versions of common <string.h> functions */
size_t my_strlen(const char *s) {
    const char *p = s;
    while (*p) p++;                 /* walk to the terminating '\0' */
    return (size_t)(p - s);
}

char *my_strcpy(char *dest, const char *src) {
    char *d = dest;
    while ((*d++ = *src++))         /* copies the '\0' too, then stops */
        ;
    return dest;
}

char *my_strcat(char *dest, const char *src) {
    my_strcpy(dest + my_strlen(dest), src);
    return dest;
}

int my_strcmp(const char *a, const char *b) {
    while (*a && *a == *b) { a++; b++; }
    return (unsigned char)*a - (unsigned char)*b;
}

int main(void) {
    char buf[40];
    my_strcpy(buf, "Cox's");
    my_strcat(buf, " Bazar");
    printf("\"%s\" has %zu characters\n", buf, my_strlen(buf));

    const char *pairs[][2] = {{"apple", "apricot"}, {"mango", "mango"}, {"zoo", "Zoo"}, {"cat", "category"}};
    for (int i = 0; i < 4; i++) {
        int r = my_strcmp(pairs[i][0], pairs[i][1]);
        printf("compare %-6s %-9s -> %s\n", pairs[i][0], pairs[i][1],
               r < 0 ? "first is smaller" : r > 0 ? "first is larger" : "equal");
    }
    return 0;
}

Output

"Cox's Bazar" has 11 characters
compare apple  apricot   -> first is smaller
compare mango  mango     -> equal
compare zoo    Zoo       -> first is larger
compare cat    category  -> first is smaller
  • my_strlen moves a pointer forward until it reaches '\0'. Subtracting the start pointer from the end pointer gives the number of characters.
  • my_strcpy uses one compact loop: *d++ = *src++ copies a character and moves both pointers on. The value of the assignment is the character just copied, so the loop stops right after copying the '\0'. The extra brackets tell the compiler the assignment inside the condition is intended.
  • my_strcat finds the end of dest and copies src there. The destination must have room for both strings plus the terminator; buf has 40 bytes.
  • my_strcmp skips matching characters, then returns the difference of the first pair that differs: negative, zero or positive. Lowercase “z” has a larger code than uppercase “Z”, so “zoo” comes after “Zoo”. “cat” is smaller than “category” because it ends first.
  • The characters are compared as unsigned char, which is what the real strcmp does, so letters outside plain ASCII also compare correctly.

Classic String Programs

#include <stdio.h>
#include <ctype.h>
#include <string.h>

void reverse(char *s) {
    for (size_t i = 0, j = strlen(s); i + 1 < j; i++, j--) {
        char t = s[i]; s[i] = s[j - 1]; s[j - 1] = t;
    }
}

int is_palindrome(const char *s) {          /* ignores case, spaces and punctuation */
    if (*s == '\0') return 1;               /* empty string: nothing to compare */
    const char *l = s, *r = s + strlen(s) - 1;
    while (l < r) {
        if (!isalnum((unsigned char)*l)) { l++; continue; }
        if (!isalnum((unsigned char)*r)) { r--; continue; }
        if (tolower((unsigned char)*l) != tolower((unsigned char)*r)) return 0;
        l++; r--;
    }
    return 1;
}

void trim(char *s) {                        /* remove spaces at both ends, in place */
    char *start = s;
    while (isspace((unsigned char)*start)) start++;
    size_t len = strlen(start);
    while (len > 0 && isspace((unsigned char)start[len - 1])) len--;
    memmove(s, start, len);
    s[len] = '\0';
}

int count_words(const char *s) {
    int words = 0, in_word = 0;
    for (; *s; s++) {
        if (isspace((unsigned char)*s)) in_word = 0;
        else if (!in_word) { in_word = 1; words++; }
    }
    return words;
}

int main(void) {
    char word[] = "Bangladesh";
    reverse(word);
    printf("reversed: %s\n", word);

    const char *tests[] = {"Madam", "Never odd or even", "Dhaka", "A man, a plan, a canal: Panama"};
    for (int i = 0; i < 4; i++)
        printf("%-32s palindrome? %s\n", tests[i], is_palindrome(tests[i]) ? "yes" : "no");

    char line[] = "   learn C   step by step   ";
    trim(line);
    printf("trimmed: [%s], %d words\n", line, count_words(line));

    char vowels_in[] = "Programming in C";
    int v = 0;
    for (char *p = vowels_in; *p; p++)
        if (strchr("aeiouAEIOU", *p)) v++;
    printf("vowels in \"%s\": %d\n", vowels_in, v);
    return 0;
}

Output

reversed: hsedalgnaB
Madam                            palindrome? yes
Never odd or even                palindrome? yes
Dhaka                            palindrome? no
A man, a plan, a canal: Panama   palindrome? yes
trimmed: [learn C   step by step], 5 words
vowels in "Programming in C": 4
  • reverse swaps the first and last characters, then moves both indexes inwards until they meet.
  • is_palindrome uses two pointers from each end, skipping anything that is not a letter or digit with isalnum, and comparing letters after tolower. That is why “A man, a plan, a canal: Panama” counts as a palindrome. An empty string is handled first, because s + strlen(s) - 1 would point before the start.
  • Characters are cast to unsigned char before calling isalnum, isspace or tolower, because passing a negative char to these functions is undefined behaviour.
  • trim finds the first non-space character and the last one, moves the text to the front with memmove, and writes a new terminator. Spaces in the middle are kept.
  • count_words counts each change from a space to a non-space character. The trimmed line has 5 words.
  • strchr("aeiouAEIOU", *p) is a quick way to ask “is this character one of these?”.

Library Functions and Their Loops

FunctionWhat the loop doesDanger
strlenCount until '\0'Runs past the end if there is no terminator
strcpyCopy characters including '\0'Overflows a destination that is too small
strcatFind the end, then copySame overflow risk, and slow when repeated
strcmpStop at the first differenceReturns any negative or positive value, not just -1 or 1

Common Mistakes

  1. Forgetting the terminator when building a string by hand. Every string needs a final '\0'.
  2. Checking strcmp(a, b) == 1. Only the sign is defined, so test > 0 or < 0.
  3. Modifying a string literal, as in char *s = "hello"; reverse(s);. Literals may be read-only; use char s[] = "hello";.
  4. Calling strlen in a loop condition on a long string, which rescans it on every iteration.

Practice Exercises

Exercise 1. Write my_strchr(const char *s, int c) that returns a pointer to the first c in s, or NULL.

Show answer
char *my_strchr(const char *s, int c) {
    for (; *s; s++)
        if (*s == (char)c) return (char *)s;
    return c == '\0' ? (char *)s : NULL;   /* the terminator counts too */
}

Exercise 2. Write to_title(char *s) that capitalises the first letter of every word: “dhaka city” becomes “Dhaka City”.

Show answer
void to_title(char *s) {
    int start = 1;
    for (; *s; s++) {
        if (isspace((unsigned char)*s)) start = 1;
        else if (start) { *s = (char)toupper((unsigned char)*s); start = 0; }
    }
}

Frequently Asked Questions

Should I use my own versions in real programs?

No. The library versions are tested and heavily optimised, often processing several bytes at a time. Writing your own is for learning and interviews.

Is there a safe version of strcpy?

Use snprintf(dest, sizeof dest, "%s", src), which never writes past the buffer and always adds a terminator. strncpy is often suggested, but it does not add a terminator when the source is too long.

Summary

  • A C string is characters followed by '\0'; string functions are loops up to it.
  • Pointer subtraction gives lengths; *d++ = *s++ copies.
  • Cast to unsigned char before calling <ctype.h> functions.
  • Always make sure the destination is big enough.

Next: Hash Tables in C.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *