Lesson 1 of 6 · Strings, Structs and Files · 2 min read · Updated

Working with strings

C has no string type. Here is what it has instead, and how to use it without getting hurt.

C has no string type. A string is an array of char ending with a \0 byte. Every string function in C depends on that terminator being there.

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

int main(void)
{
    char first[20] = "Priya";
    char last[20]  = "Raman";
    char full[50];

    strcpy(full, first);
    strcat(full, " ");
    strcat(full, last);

    printf("%s\n", full);
    printf("%d characters\n", (int) strlen(full));

    if (strcmp(first, last) != 0) {
        printf("The names differ\n");
    }

    return 0;
}
Output
Priya Raman
11 characters
The names differ

The functions you will use

  • strlen(s) — how many characters, not counting the terminator.
  • strcpy(dest, src) — copy src into dest.
  • strcat(dest, src) — stick src onto the end of dest.
  • strcmp(a, b) — 0 if identical. Not a true/false answer, so compare against 0.

Warning

strcpy and strcat do not check whether the destination is big enough. Writing past the end is a buffer overflow — historically the cause of a great many security holes. Make the destination generously large, and prefer snprintf when you can.

Reading a line of text

c
char name[50];

printf("Your name: ");
fgets(name, sizeof(name), stdin);

/* fgets keeps the newline; trim it off. */
name[strcspn(name, "\n")] = '\0';

printf("Hello, %s!\n", name);

Note

Use fgets rather than scanf("%s") for text. scanf("%s") stops at the first space and has no idea how big your buffer is. fgets takes the size and respects it.

What does strcmp(a, b) return when the strings are identical?

Create a free account to save your progress, or sign in.