CC

C: Strings – code examples

Contents

Reading a line safely

Strings#fgets#input#stdin#security
Use case: Read user input from the keyboard without risking a buffer overflow.
#include <stdio.h>
#include <string.h>

int main(void) {
    char zeile[64];
    printf("Name? ");
    if (fgets(zeile, sizeof zeile, stdin) == NULL) return 1;
    zeile[strcspn(zeile, "\n")] = '\0';
    printf("Hello, %s!\n", zeile);
    return 0;
}

fgets limits the input to the buffer size. strcspn finds the newline, which we replace with the null byte. Never use gets.

Reversing a string

Strings#string#reverse#char
Use case: Process strings in place, e.g. palindrome checks or reversing numbers as text.
#include <stdio.h>
#include <string.h>

void umkehren(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 main(void) {
    char text[] = "Hello";
    umkehren(text);
    printf("%s\n", text);
    return 0;
}

Two indices run from the outside inward and swap characters. The string must be modifiable (char text[], not char *text = "...").

Formatted strings with snprintf

Strings#snprintf#format#security
Use case: Safely assemble file names, log lines or messages.
#include <stdio.h>

int main(void) {
    char name[32];
    int n = snprintf(name, sizeof name, "bericht_%04d_%s.txt", 7, "mai");
    printf("%s (%d characters)\n", name, n);

    char klein[8];
    snprintf(klein, sizeof klein, "%s", "way too long");
    printf("%s\n", klein);
    return 0;
}

snprintf never writes more than sizeof puffer bytes and always appends a null byte. The return value is the length that would have been needed *without* the limit – that is how you detect truncation.

Counting letters (histogram)

Strings#ctype#histogram#character#array
Use case: Text statistics, frequency analysis or simple cipher analysis.
#include <stdio.h>
#include <ctype.h>

int main(void) {
    const char *text = "Programming in C";
    int zaehler[26] = {0};
    for (const char *p = text; *p != '\0'; p++) {
        if (isalpha((unsigned char)*p)) zaehler[tolower((unsigned char)*p) - 'a']++;
    }
    for (int i = 0; i < 26; i++) {
        if (zaehler[i] > 1) printf("%c: %d\n", 'a' + i, zaehler[i]);
    }
    return 0;
}

An array serves as the counter; zeichen - 'a' converts a letter into an index. Cast to unsigned char for ctype.h functions.