Skip to content
FollowtheDamnCode

String Functions

strlen, strcpy, strcat, and strcmp.

5 minute read

Big idea

<string.h> has ready-made functions for the jobs you'd otherwise loop over by hand: length, copy, join, compare.

The four you'll use most

FunctionDoesExample
strlen(s)length, not counting '\0'strlen("cat") → 3
strcpy(dest, src)copies src into deststrcpy(name, "Ravi");
strcat(dest, src)adds src onto the end of deststrcat(greeting, "!");
strcmp(a, b)compares — 0 means equalstrcmp("a", "a") → 0
All four in one go
#include <stdio.h>
#include <string.h>

int main(void) {
    char first[30];
    strcpy(first, "Ada");
    char full[60];
    strcpy(full, first);
    strcat(full, " Lovelace");
    printf("%s has %zu letters\n", full, strlen(full));
    if (strcmp(first, "Ada") == 0) {
        printf("Same name\n");
    }
    return 0;
}
output
Ada Lovelace has 12 letters
Same name

Run and edit it in the app.

%zu is the printf code for strlen's result type (size_t, a size that can't be negative).

Watch it

You can't use = or == on strings

Arrays can't be assigned or compared as a whole:

name = "Ravi";        // ✗ doesn't compile — use strcpy
if (a == b)           // ✗ compares ADDRESSES, not text — use strcmp
Fix the bug: "hello" should match
#include <stdio.h>
#include <string.h>

int main(void) {
    char typed[10] = "hello";
    char secret[10] = "hello";
    if (typed == secret) {
        printf("match\n");
    } else {
        printf("no match\n");
    }
    return 0;
}
output
match

Run and edit it in the app.

strcmp's answer

strcmp(a, b) returns 0 when equal, a negative number when a comes first in dictionary order, and a positive number when a comes after. So strcmp("apple", "banana") < 0.

Make room first

strcpy and strcat don't check sizes — the destination must be big enough for the result plus '\0'. strncpy and strncat take a maximum length, and snprintf(dest, sizeof dest, "%s %s", a, b) builds a string safely in one step.

Predict: strlen and sizeof
#include <stdio.h>
#include <string.h>

int main(void) {
    char word[20] = "web";
    printf("%zu %zu\n", strlen(word), sizeof word);
    return 0;
}
What does it print? Show the answer
3 20

Run and edit it in the app.

strlen counts the text. sizeof measures the whole array, used or not.

Think of it like

A toolbox for text. You could build a hammer from scratch every time — or grab the one in <string.h>.

🕷️ Spidey-sense: strcmp(disguise, "Peter Parker") == 0 — the day that's true in public, my secret identity is over. Always compare strings with strcmp, never with ==.

Key terms

  • <string.h> — The header with C's string functions.
  • strlen / strcpy / strcat / strcmp — Length, copy, join, compare.
  • size_t — The unsigned type used for sizes and lengths.

Check yourself

What is strlen("code")?

strcmp(a, b) returns 0 when…

How do you put "Ravi" into char name[20]?