SyntaxStudy
Sign Up
C C Strings and <string.h>
C Beginner 1 min read

C Strings and <string.h>

In C, a string is a null-terminated array of `char` values. The null terminator is the character `'\0'` (integer value 0) and signals the end of the string. A string literal like `"hello"` is stored as the six bytes `h`, `e`, `l`, `l`, `o`, `\0`. The null terminator means that a char array holding a string of `n` characters needs at least `n+1` bytes. Forgetting the space for the null terminator leads to buffer overflows. The `` header declares the standard string functions. `strlen()` returns the number of characters before the null terminator. `strcpy()` and `strncpy()` copy strings. `strcat()` and `strncat()` concatenate. `strcmp()` compares two strings lexicographically, returning 0 if equal, negative if the first is less, positive if greater. `strchr()` and `strstr()` search for characters and substrings. The `n`-variants (`strncpy`, `strncat`, `strncmp`) accept a maximum length argument and are safer than their unbounded counterparts. Even better, on systems that support it, `strlcpy()` and `strlcat()` always null-terminate the destination. When reading strings from user input, always use `fgets()` instead of `gets()` — `gets()` was so dangerous it was removed from the C11 standard entirely.
Example
#include <stdio.h>
#include <string.h>

int main(void)
{
    char  src[] = "Hello, World";
    char  dest[64];
    char  upper[64];

    /* strlen does NOT count the null terminator */
    printf("strlen(\"%s\") = %zu\n", src, strlen(src));   /* 12 */

    /* strcpy: destination must be large enough */
    strcpy(dest, src);
    printf("strcpy: \"%s\"\n", dest);

    /* strncpy: safer — limits bytes copied */
    strncpy(upper, src, sizeof(upper) - 1);
    upper[sizeof(upper) - 1] = '\0';   /* always null-terminate! */

    /* strcmp: 0 means equal */
    printf("strcmp same:     %d\n", strcmp(src, dest));    /* 0  */
    printf("strcmp 'a','b':  %d\n", strcmp("a", "b"));    /* <0 */

    /* strcat: appending */
    char greeting[64] = "Hello";
    strncat(greeting, ", C!", sizeof(greeting) - strlen(greeting) - 1);
    printf("strcat: \"%s\"\n", greeting);

    /* strchr: find first occurrence of character */
    char *comma = strchr(src, ',');
    if (comma)
        printf("Found ',' at position %td\n", comma - src);

    /* strstr: find substring */
    char *world = strstr(src, "World");
    if (world)
        printf("Found \"World\" at position %td\n", world - src);

    /* Manually uppercase using pointer walk */
    char *p = upper;
    while (*p) {
        if (*p >= 'a' && *p <= 'z') *p -= 32;
        p++;
    }
    printf("upper: \"%s\"\n", upper);

    return 0;
}