Lesson 16 of 23

Strings: Character Arrays

11 min 30 XP

In C a string is a char array ending with '\0' (the null character). "Hi" really takes 3 bytes: 'H', 'i', '\0'. <string.h> provides strlen, strcpy, strcat and strcmp.

Example: edit me and press Run

Output Loading C (first time takes a few seconds)
Press Run to see the result here.

Use fgets to read a whole line, including spaces. It keeps the trailing \n, which you can remove with strcspn.

Example: edit me and press Run

Output Loading C (first time takes a few seconds)
Press Run to see the result here.

You can't compare strings with == (that compares addresses). strcmp(a, b) == 0 means they are equal.

Challenge

+30 XP

Read a line with fgets and count its vowels, consonants and spaces. Input: Hello World Output: Vowels: 3 Consonants: 7 Spaces: 1

Output Loading C (first time takes a few seconds)
Press Run to see the result here.