Skip to content
C

String Operations

Use string.h helpers for length, copy, concat, compare, and tokenize.

By EZ4Code Team
stringstring-h

Code

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

int main(void) {
    char src[] = "Hello, World!";
    char dst[32];

    // Length (excludes terminator)
    printf("len      = %zu\n", strlen(src));

    // Copy
    strcpy(dst, src);
    printf("copy     = %s\n", dst);

    // Concatenation
    strcat(dst, " Goodbye.");
    printf("concat   = %s\n", dst);

    // Comparison
    printf("cmp      = %d\n", strcmp("abc", "abd"));

    // Substring search
    char *p = strstr(src, "World");
    if (p) printf("found at offset %ld\n", (long)(p - src));

    // Tokenize
    char csv[] = "a,b,c,d";
    char *tok = strtok(csv, ",");
    while (tok) { printf("tok = %s\n", tok); tok = strtok(NULL, ","); }

    return 0;
}

Explanation

C strings are NUL-terminated char arrays operated on by string.h functions. strlen, strcpy, strcat, strcmp, and strstr cover the common length, copy, concat, compare, and search operations. strtok splits a string in place by replacing delimiters with NUL bytes and must be re-entered with NULL to continue tokenizing.

More C Snippets