Strings

Strings as char arrays ending in \0, <string.h>, snprintf, and POSIX regular expressions.

Runs in Zerethon IDE · C (GCC 14) Official C documentation ↗
main.c
#include <ctype.h>
#include <regex.h>
#include <stdio.h>
#include <string.h>

int main(void) {
    char name[32] = "Ada";
    strcat(name, " Lovelace");
    printf("%s has %zu characters\n", name, strlen(name));
    printf("%d %d\n", strcmp("abc", "abc") == 0, strncmp(name, "Ada", 3) == 0);

    char upper[32];
    for (size_t i = 0; i <= strlen(name); i++) upper[i] = (char) toupper((unsigned char) name[i]);
    printf("%s\n", upper);

    char line[] = "a,b,c";
    for (char *part = strtok(line, ","); part; part = strtok(NULL, ",")) printf("[%s]", part);
    printf("\n");

    char buf[16];
    snprintf(buf, sizeof buf, "%03d|%.2f", 7, 3.14159);
    puts(buf);

    regex_t re;
    regmatch_t m[2];
    const char *text = "order 7 pending";
    regcomp(&re, "order ([0-9]+)", REG_EXTENDED);
    if (regexec(&re, text, 2, m, 0) == 0) printf("%.*s\n", (int) (m[1].rm_eo - m[1].rm_so), text + m[1].rm_so);
    regfree(&re);
    return 0;
}

Output

Ada Lovelace has 12 characters
1 1
ADA LOVELACE
[a][b][c]
007|3.14
7
  • Compare with strcmp(a, b) == 0; a == b compares addresses.
  • Make the array big enough for the text plus the final \0. Prefer snprintf to sprintf and strcpy: it never writes past the buffer.
  • <regex.h> (POSIX) is available here; it is not part of standard C.