Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

C Strings

C has no separate string type. A string is an array of char that ends with a special character, the null terminator '\0', which marks where the text stops.

Creating a string

#include <stdio.h>

int main(void) {
    char greeting[] = "Hello";
    printf("%s\n", greeting);
    printf("First letter: %c\n", greeting[0]);
    printf("Array size: %zu\n", sizeof(greeting));
    return 0;
}
Output
Hello
First letter: H
Array size: 6

"Hello" has 5 letters, but the array has 6 elements: the compiler adds '\0' at the end. A string array always needs room for that extra character.

Changing characters

A string in an array can be changed one character at a time:

#include <stdio.h>

int main(void) {
    char word[] = "cat";
    word[0] = 'b';
    printf("%s\n", word);
    return 0;
}
Output
bat

But a whole string cannot be assigned with = after the declaration: word = "dog"; is an error. Copy strings with strcpy, shown in the String Functions topic.

Looping over a string

The terminator lets a loop find the end without knowing the length:

#include <stdio.h>

int main(void) {
    char text[] = "programming";
    int vowels = 0, length = 0;
    for (int i = 0; text[i] != '\0'; i++) {
        length++;
        char c = text[i];
        if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
            vowels++;
        }
    }
    printf("%s has %d letters and %d vowels\n", text, length, vowels);
    return 0;
}
Output
programming has 11 letters and 3 vowels

Strings with a fixed size

You can also give the size yourself, leaving room for longer text later: char name[20] = "Asha";. Unused elements are set to '\0'. Writing more characters than the array holds is a serious bug, one of the most common in C, so always make string arrays large enough and use functions that respect the size.

Characters and strings are different

Single quotes make one character, 'A'; double quotes make a string, "A", which is two characters ('A' and '\0'). Use %c to print a character and %s to print a string.

Practice exercises

  1. Count how many times the letter m appears in "programming".
  2. Change every letter of a word to upper case by subtracting 32 from lower-case letters (look at an ASCII table to see why).
  3. Print a word backwards with a loop that starts at its last letter.