String Functions in C

The standard library’s string.h header provides many useful string-related functions. Here are some examples to give you a sense of the available functions.

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

// We define a helper function to print boolean values
void print_bool(const char* prefix, int value) {
    printf("%s%s\n", prefix, value ? "true" : "false");
}

int main() {
    // Here's a sample of the functions available in string.h and ctype.h.
    // Since these are functions from the standard library, not methods on
    // the string object itself, we need to pass the string in question as
    // an argument to the function.

    print_bool("Contains:  ", strstr("test", "es") != NULL);
    printf("Count:     %d\n", (int)strlen("test") - (int)strlen(strstr("test", "t")));
    print_bool("HasPrefix: ", strncmp("test", "te", 2) == 0);
    print_bool("HasSuffix: ", strcmp(strrchr("test", 's'), "st") == 0);
    printf("Index:     %d\n", (int)(strchr("test", 'e') - "test"));

    // Join is not available in C, so we'll implement it
    char* join(const char* strings[], int count, const char* delimiter) {
        size_t total_length = 0;
        for (int i = 0; i < count; i++) {
            total_length += strlen(strings[i]);
        }
        total_length += strlen(delimiter) * (count - 1);

        char* result = malloc(total_length + 1);
        result[0] = '\0';

        for (int i = 0; i < count; i++) {
            strcat(result, strings[i]);
            if (i < count - 1) {
                strcat(result, delimiter);
            }
        }

        return result;
    }

    const char* strings[] = {"a", "b"};
    char* joined = join(strings, 2, "-");
    printf("Join:      %s\n", joined);
    free(joined);

    printf("Repeat:    %.*s\n", 5, "aaaaa");
    
    char replace_str[] = "foo";
    for (char* p = replace_str; *p; p++) {
        if (*p == 'o') *p = '0';
    }
    printf("Replace:   %s\n", replace_str);

    char* token = strtok("a-b-c-d-e", "-");
    printf("Split:     ");
    while (token != NULL) {
        printf("%s ", token);
        token = strtok(NULL, "-");
    }
    printf("\n");

    char lower[] = "TEST";
    for (char* p = lower; *p; p++) *p = tolower(*p);
    printf("ToLower:   %s\n", lower);

    char upper[] = "test";
    for (char* p = upper; *p; p++) *p = toupper(*p);
    printf("ToUpper:   %s\n", upper);

    return 0;
}

To run the program, compile the code and then execute the resulting binary:

$ gcc string_functions.c -o string_functions
$ ./string_functions
Contains:  true
Count:     2
HasPrefix: true
HasSuffix: true
Index:     1
Join:      a-b
Repeat:    aaaaa
Replace:   f00
Split:     a b c d e 
ToLower:   test
ToUpper:   TEST

Note that C doesn’t have built-in string objects or methods, so we use functions from the standard library to manipulate strings. Some operations, like Join and Replace, are implemented manually or with slight modifications to match C’s capabilities. The Split function in C modifies the original string, unlike in some other languages where it returns a new array.