Lesson 67 +10 XP

String Functions

String Functions

The <string.h> header has ready-made tools for working with strings.

strlen: length

#include <string.h>

char greeting[] = "Hello";
printf("%d\n", strlen(greeting));   // 5

strlen counts characters up to the null.

strcat: join

char first[] = "Hello ";
char second[] = "World";
strcat(first, second);
printf("%s", first);    // Hello World

strcat appends the second string to the first.

strcpy: copy

char source[] = "Hello";
char target[20];
strcpy(target, source);

Copy a string into another.

strcmp: compare

if (strcmp(s1, s2) == 0) {
    printf("Equal!");
}

strcmp returns 0 when the strings are equal.

The include

All of these need #include <string.h>. Note: strcmp matters because == compares pointers, not content.

TL;DR

  • strlen gives length; strcat joins; strcpy copies.
  • strcmp compares - 0 means equal.
  • All live in <string.h>.
  • Strings don't compare with ==.