Learn/C/8. Strings and a small project
Lesson 8 of 15
Sign in

C, lesson 8

Strings and a small project

C has no separate string type. A string is an array of char that ends with a special character, the null terminator '\0' (a byte with value 0). Every string function walks the array until it meets that zero byte.

Forgetting room for the terminator is the most common C string bug. A buffer of size 20 holds at most 19 visible characters.

Reading a whole line

scanf("%s", ...) stops at the first space, so it can't read "Ada Lovelace". Use fgets, which reads a whole line and never writes past the size you give it:

fgets returns a null pointer (nullptr, or the older NULL) when there is nothing left to read. It keeps the at the end of the line, and gives the index of the first newline (or the end of the string), which you then overwrite with .

2 exercises to try what you just read.

Exercise 1

Name badge

Press Ctrl Enter or Check to test your code.

Exercise 2

Word stats

Press Ctrl Enter or Check to test your code.

'\n'
strcspn(line, "\n")
'\0'

string.h

Include <string.h> for the standard helpers:

FunctionWhat it does
strlen(s)number of characters before the '\0'
strcmp(a, b)0 if equal, negative if a sorts first, positive otherwise
strchr(s, c)pointer to the first c in s, or a null pointer
strstr(s, t)pointer to the first copy of t inside s, or a null pointer
snprintf(buf, size, fmt, ...)printf into a buffer, never writing more than size bytes

You cannot compare strings with == (that compares addresses) or copy them with =. Use strcmp and snprintf (or strcpy when you are certain the target is big enough).

Characters and ctype.h

A char is a small integer, so you can loop over a string index by index and inspect each character. <ctype.h> classifies and converts characters: isalpha, isdigit, isspace, isupper, toupper, tolower. Pass them an unsigned char value, because a plain char can be negative for non-English letters and that is undefined behaviour.

size_t is the unsigned type that strlen and sizeof return. Print it with %zu.

Putting it together

A typical text-processing program reads a line, walks it character by character, and keeps a little state: "am I inside a word right now?", "how long is the current word?". Small helper functions keep main readable. The project below does exactly that.

Further reading

  • cppreference: Null-terminated byte strings
  • cppreference: fgets
  • cppreference: strcspn
  • GNU C Manual: String Constants

Read one line containing a person's full name (at most 80 characters). Print the name in upper case on the first line, and on the second line the number of letters in it (spaces, hyphens and other non-letters don't count).

Time for a small project that uses everything so far. Read one line of text (at most 200 characters). Words are runs of letters separated by one or more spaces. Print:

  1. Words: <count>
  2. Longest: <word>, the longest word (the first one if several tie), or Longest: none if the line has no words
  3. Vowels: <count>, the number of vowels a e i o u in either case

Suggested plan: write a helper bool is_vowel(char c). Walk the line once; when a word starts, remember its start index; when it ends, compare its length with the best so far. Print the longest word with %.*s, which takes a length and a pointer: printf("%.*s", len, line + start).

char word[] = "cat";      // 4 bytes: 'c' 'a' 't' '\0'
char name[20] = "Ada";    // room for 19 characters plus the terminator
char line[100];
if (fgets(line, sizeof line, stdin) != nullptr) {
    line[strcspn(line, "\n")] = '\0';   // remove the newline fgets keeps
}
if (strcmp(answer, "yes") == 0) {
    puts("Confirmed");
}
char greeting[64];
snprintf(greeting, sizeof greeting, "Hi, %s!", name);
for (size_t i = 0; line[i] != '\0'; i++) {
    unsigned char c = line[i];
    if (isdigit(c)) {
        digits++;
    }
    line[i] = toupper(c);
}
Input:
Ada Lovelace
Output:
ADA LOVELACE
Letters: 11
Input:
the quick brown fox jumps
Output:
Words: 5
Longest: quick
Vowels: 6