Strings in C: Working with Text in char Arrays

MODULE 3 • LESSON 08

Names, addresses, passwords, product codes, messages: most of the data people care about is text. Python and Java have a built-in string type, but C does not. In C a string is simply an array of char that ends with a special character, the null terminator '\0'. Everything you learned about arrays in Lesson 07 still applies, plus a few rules and a library of string functions in string.h.

Understanding that a string is “characters in an array, then \0” explains almost every string bug in C: names that print with garbage after them, strings that cannot be compared with ==, and programs that crash because a name was longer than the array. In this lesson you will declare, read, print, copy, join, compare and process strings, both with library functions and character by character.

What you will learn

  • How a string is stored as a char array ending in the null terminator, and how big the array must be.
  • How to output strings with printf and puts, and read them with scanf and fgets.
  • How to use strlen, strcpy, strcat and strcmp, and why = and == do not work on strings.
  • How to process a string one character at a time, using ctype.h functions such as toupper and isdigit.
  • How to avoid buffer overflow and missing terminators.

Part 1: Strings are char arrays

char name[10] = "Ravi";

This sets aside 10 bytes. The characters R, a, v, i go into name[0] to name[3], and the compiler adds '\0' (the character with code 0) in name[4]. The remaining bytes are unused (set to 0 here because of the initialiser). The terminator is how every string function knows where the text ends, since an array does not store its own length.

Index012345 … 9
name[i]‘R’‘a’‘v’‘i’‘\0’unused

So the array must be at least one byte longer than the longest text it will hold: a 10-byte array holds text of up to 9 characters. If you leave out the size, char last[] = "Persad";, the compiler makes the array exactly big enough: 7 bytes. Remember the difference between 'A' (one char, single quotes) and "A" (a string of two bytes: A and \0, double quotes).

An array name cannot be assigned to after it is declared: name = "Kemal"; is a compile error. To put new text into an existing array, use strcpy (Part 3), or set the characters one by one.

Part 2: Output and input

Output is easy: printf("%s", name); prints characters from name[0] up to (not including) the \0, and puts(name); does the same and adds a new line. Width and alignment work as for numbers: %-12s left-aligns a name in 12 columns, ideal for report tables (Lesson 04).

Input needs more care. scanf("%19s", name); reads one word: it skips leading whitespace and stops at the first space. Notice there is no address-of operator: the name of an array already stands for the address of its first element. The 19 is a maximum width that stops scanf writing more than 19 characters plus \0 into a 20-byte array; without it, a long word would overflow the array.

To read a whole line, including spaces, use fgets(name, sizeof(name), stdin);. It reads up to one less than the size given, adds \0, and never overflows. It also keeps the newline from the Enter key if there was room, so programs usually remove it. And beware the input buffer from Lesson 04: if a scanf(“%d”) came just before, the leftover newline makes fgets return an empty line at once. Reading the rest of that line first (for example with a loop of getchar until ‘\n’) fixes it. Never use the old function gets: it cannot limit the length and has been removed from the C language.

Worked example 1: reading a full name

The user typed Keisha Ann Mohammed.

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

int main(void)
{
    char name[40];
    int i, len;

    printf("Full name: ");
    fgets(name, sizeof(name), stdin);
    len = strlen(name);
    if (len > 0 && name[len - 1] == '\n') {
        name[len - 1] = '\0';
        len--;
    }

    printf("\nHello, %s!\n", name);
    printf("Length: %d\n", len);
    printf("Initials: %c", name[0]);
    for (i = 1; i < len; i++) {
        if (name[i - 1] == ' ') {
            printf("%c", name[i]);
        }
    }
    printf("\n");
    return 0;
}

Sample input: Keisha Ann Mohammed

Output:

Full name: 
Hello, Keisha Ann Mohammed!
Length: 19
Initials: KAM

The if after fgets replaces the trailing newline with \0. The initials loop prints every character that follows a space: it uses name[i − 1], which is why it starts at i = 1.

Part 3: The string library

#include <string.h> gives you ready-made functions. The four you must know are:

FunctionWhat it doesExampleResult
strlen(s)number of characters before the \0strlen(“Ravi”)4
strcpy(dest, src)copies src (and its \0) into deststrcpy(full, “Ravi”);full holds Ravi
strcat(dest, src)adds src onto the end of deststrcat(full, ” P.”);full holds Ravi P.
strcmp(a, b)compares: 0 if equal, negative if a comes first, positive if b comes firststrcmp(“Ann”, “Bob”)a negative number

Why not = and ==? An array name stands for an address. if (name == "Ravi") compiles but compares two addresses, which are almost never equal, so it is false even when the text matches. Always test if (strcmp(name, "Ravi") == 0). strcmp compares character codes from the left until two differ, so upper-case letters (codes 65 to 90) come before lower-case ones (97 to 122) and “Zebra” sorts before “apple”. That is why programs often convert to one case before comparing.

strcpy and strcat do not know how big dest is. If the result does not fit, they write past the end of the array: a buffer overflow. Always make the destination big enough for the longest possible result plus the \0. (strncpy and strncat take a maximum length, but have their own traps; checking the length with strlen before copying is clearer.)

Worked example 2: library functions

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

int main(void)
{
    char first[20] = "Ravi";
    char last[] = "Persad";
    char full[40];

    printf("%s has %d letters\n",
           first, (int) strlen(first));
    printf("last uses %d bytes\n",
           (int) sizeof(last));

    strcpy(full, first);
    strcat(full, " ");
    strcat(full, last);
    printf("full: %s (%d)\n", full,
           (int) strlen(full));

    printf("cmp1: %d\n",
           strcmp("Ann", "Ann") == 0);
    printf("cmp2: %d\n",
           strcmp("Ann", "Bob") < 0);
    printf("cmp3: %d\n",
           strcmp("ann", "Ann") > 0);
    return 0;
}

Output:

Ravi has 4 letters
last uses 7 bytes
full: Ravi Persad (11)
cmp1: 1
cmp2: 1
cmp3: 1

strlen returns a value of type size_t, so it is cast to int for %d. sizeof(last) gives the array size, 7, one more than strlen. The three cmp lines print the truth of each comparison (1 for true): strcmp gives 0 for equal strings, a negative value when the first comes before the second, and a positive value for “ann” against “Ann”, because lower-case a has a larger code than upper-case A.

Try it 1Inside a string

This is char s[12]. Tap statements to run them on s and watch the memory, the \0 (teal) and what printf and strlen see. The dashed boxes belong to other variables. Hit all five targets; Reset brings back an uninitialised array.


Statements run so far


    Part 4: Working character by character

    Because a string is an array, you can loop over it. The standard loop does not need the length at all; it stops at the terminator: for (i = 0; s[i] != '\0'; i++). Inside, s[i] is an ordinary char that you can test and change.

    #include <ctype.h> provides helpers for single characters: isalpha(c), isdigit(c), isspace(c), isupper(c) and islower(c) return true (non-zero) or false (0); toupper(c) and tolower(c) return the converted character, leaving non-letters unchanged. These make tasks such as validation (“a product code must be two letters then three digits”), counting and case conversion short and clear.

    Worked example 3: counting, reversing and converting

    #include <stdio.h>
    #include <ctype.h>
    #include <string.h>
    
    int main(void)
    {
        char s[] = "Grade 11 rocks!";
        char r[40];
        int i, n, vow = 0, dig = 0;
    
        n = strlen(s);
        for (i = 0; s[i] != '\0'; i++) {
            char c = tolower(s[i]);
            if (c == 'a' || c == 'e' || c == 'i'
                || c == 'o' || c == 'u') {
                vow++;
            } else if (isdigit(s[i])) {
                dig++;
            }
        }
        printf("Vowels: %d, digits: %d\n",
               vow, dig);
    
        for (i = 0; i < n; i++) {
            r[i] = s[n - 1 - i];
        }
        r[n] = '\0';
        printf("Reversed: %s\n", r);
    
        for (i = 0; s[i] != '\0'; i++) {
            s[i] = toupper(s[i]);
        }
        printf("Upper: %s\n", s);
        return 0;
    }
    

    Output:

    Vowels: 3, digits: 2
    Reversed: !skcor 11 edarG
    Upper: GRADE 11 ROCKS!

    Look at three details. The vowel test converts each character to lower case first, so both A and a count. The reverse loop copies s[n − 1 − i], not s[n − i], which would start with the \0. And after building r character by character the program must add the terminator itself with r[n] = '\0';, because only string literals and library functions add it automatically.

    Try it 2String loop tracer

    Choose a program and step through it. Strings are shown as char arrays; \0 marks the terminator.

    Output

    
    

    Part 5: Lists of strings and validating text

    A list of names is an array of strings, which in C is a two-dimensional char array: char name[30][21]; holds 30 names of up to 20 characters each. name[i] is the whole i-th string (use it with %s, strcpy and strcmp), and name[i][0] is its first letter. Reading them is a loop of scanf("%20s", name[i]); or fgets calls. Sorting names alphabetically uses exactly the same swapping logic as sorting numbers, except that the comparison is strcmp(name[j], name[j + 1]) > 0 and the swap needs a temporary string and three strcpy calls.

    Text input often has to follow a format: a product code of two capital letters then three digits, a student ID of exactly 6 digits, a password with at least one digit. Each rule becomes a test on the length (strlen) or on particular characters (ctype.h). This is the format check from Module 2’s validation, now in C. Write the checks as a small function that returns 1 for valid and 0 for invalid, so the main program stays readable.

    Worked example 4: checking product codes

    #include <stdio.h>
    #include <ctype.h>
    #include <string.h>
    
    int valid(char c[])
    {
        int i;
        if (strlen(c) != 5) {
            return 0;
        }
        for (i = 0; i < 5; i++) {
            if (i < 2 && !isupper(c[i])) {
                return 0;
            }
            if (i >= 2 && !isdigit(c[i])) {
                return 0;
            }
        }
        return 1;
    }
    
    int main(void)
    {
        char code[4][8] = {"AB123", "ab123",
                           "AB12", "XY9Z0"};
        int i;
    
        for (i = 0; i < 4; i++) {
            printf("%-6s %s\n", code[i],
                   valid(code[i]) ? "valid"
                                  : "rejected");
        }
        return 0;
    }
    

    Output:

    AB123  valid
    ab123  rejected
    AB12   rejected
    XY9Z0  rejected

    The function valid returns 0 as soon as any rule fails, and 1 only if every character passed. The codes are stored in char code[4][8], four strings of up to 7 characters, and code[i] passes one whole string to the function. The ? : in the printf is C’s conditional operator: it chooses "valid" when the test is true and "rejected" otherwise. You will write functions like valid yourself in Lesson 09.

    Strings and numbers. The text "125" is not the number 125: it is the characters 1, 2, 5 and a terminator. stdlib.h provides atoi("125") (gives the int 125) and atof("12.5") (gives a double), and sprintf(buf, "%d", n); does the reverse, writing formatted text into a char array instead of the screen. A digit character can also be turned into its value with c - '0', because the digit codes are consecutive: '7' − '0' is 7.

    Designing a string algorithm: is it a palindrome?

    A palindrome reads the same forwards and backwards, like "level" or "Racecar". Before writing code, design the algorithm as in Module 2. One approach uses two indexes: left starts at 0 and right starts at strlen(s) − 1. While left is less than right, compare s[left] and s[right] (after converting both to lower case). If they differ, the word is not a palindrome and you can stop. Otherwise move left one step right and right one step left. If the indexes meet without a mismatch, it is a palindrome.

    Trace it with "Racecar": compare R and r (equal after tolower), a and a, c and c, then left = right = 3, so the loop stops: a palindrome. With "radio": r and o differ at once, so the answer is no after a single comparison. Notice that the algorithm never needs a second array, checks at most half the characters, and handles words of odd and even length without any special case. A flag variable such as int ok = 1;, set to 0 on a mismatch and used in the loop condition, is a tidy way to stop early, just like pos in the linear search of Lesson 07. Homework question 1 asks you to turn this design into a program.

    Common string errors

    ErrorExampleCorrection
    Array too smallchar code[5] = "AB123";char code[6]: allow for \0
    Assigning with =name = "Ava";strcpy(name, "Ava");
    Comparing with ==if (pw == "abc")if (strcmp(pw, "abc") == 0)
    Missing terminatorbuilding r but never setting r[n] = '\0'add the \0 after the last character
    Address-of with %sscanf("%s", &name);scanf("%19s", name);
    Single vs double quoteschar c = "Y"; or strcpy(s, 'Y');char c = 'Y'; strcpy(s, "Y");
    Unlimited inputscanf("%s", name); or gets(name);scanf with a width, or fgets

    Try it 3String practice

    Pick a mode. "Lengths" asks about strlen, array sizes and indexes. "strcmp" asks whether strcmp returns 0, a negative or a positive value.

    Summary

    IdeaRemember
    StorageA string is a char array ending in \0; the array needs length + 1 bytes.
    Outputprintf("%s"), puts; %-12s for aligned columns.
    Inputscanf("%19s", s) for one word (no address-of); fgets(s, size, stdin) for a line.
    Librarystrlen, strcpy, strcat, strcmp (0 means equal); never = or == on strings.
    Loopsfor (i = 0; s[i] != '\0'; i++); ctype.h for toupper, isdigit and friends.
    SafetyMake arrays big enough; add \0 when building strings yourself.

    Review questions

    1. How many bytes are needed to store the string "Chaguanas"? Explain.

    Show answer

    10: nine characters plus one byte for the null terminator \0.

    2. State the difference between 'Q' and "Q" in C.

    Show answer

    'Q' is a single char (one byte). "Q" is a string: a char array holding Q followed by \0 (two bytes).

    3. Why does scanf("%s", town) not need the address-of operator?

    Show answer

    An array name already stands for the address of its first element.

    4. A student writes if (answer == "yes"). Explain why it fails and correct it.

    Show answer

    It compares the addresses of two arrays, not their contents. Use if (strcmp(answer, "yes") == 0).

    5. Write code that joins first and last (with a space between) into full, given char first[20], last[20], full[45].

    Show answer

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

    6. Write a loop that counts the digits in a string s.

    Show answer

    count = 0;
    for (i = 0; s[i] != '\0'; i++) {
    if (isdigit(s[i])) count++;
    }

    7. What is a buffer overflow, and how can it happen with strcpy?

    Show answer

    Writing past the end of an array. strcpy copies the whole source and its \0 without checking the destination size, so a source that is too long overwrites the memory after the destination.

    8. Give ONE advantage of fgets over scanf("%s") for reading a name.

    Show answer

    fgets reads a whole line including spaces (for example a first and last name) and limits the number of characters to the array size.

    Homework

    1. Write a program that reads a word and prints whether it is a palindrome (reads the same backwards), ignoring case.
    2. Write a program that reads a password and checks that it is at least 8 characters long and contains at least one digit and one upper-case letter.
    3. Read a sentence with fgets and print the number of words (count the places where a space is followed by a non-space).
    4. Store five student names in a two-dimensional char array, char name[5][20], read them in, and print the name that comes first alphabetically using strcmp.
    5. Explain, with a diagram of memory, what goes wrong in: char s[4]; strcpy(s, "Hello");

    Mastery quiz: Strings in C

    This 10-question quiz is separate from the short Quick quiz at the end of the lesson. Score 8/10 or higher to earn this lesson’s badge. Your best score is saved in this browser on this device.

    Mastery quiz: Strings in C: Working with Text in char Arrays

    Your course badges: loading saved progress…

    View badges

      No course badges earned yet. Score 8/10 in a lesson quiz to earn its badge.

      Saved in this browser on this device. Clearing browser data may remove your badges.

      Answer all 10 questions. Earn this lesson’s badge at 8/10 or higher. Read the explanations, revisit the Try it activities and retry as often as you need. These are self-study badges, not formal grades.

      1. What marks the end of a string in C?
      2. What is the smallest array that can hold "Arima"?
      3. What does strlen("San Juan") return?
      4. Which statement correctly puts "Ava" into char name[10] after it has been declared?
      5. strcmp(a, b) returns 0 when...
      6. Which reads a whole line, including spaces, safely?
      7. Which header file declares strcpy and strcmp?
      8. What does toupper('g') return?
      9. After building a string r one character at a time, what must you add?
      10. What happens with strcpy if the destination array is too small?

      Exam tips

      CAPE 2024 Unit 1 Paper 02, Question 5(b). Correcting a printf that uses the string specifier for an integer, and a string literal without double quotes. For each fix, state the rule: %s is only for strings, and string literals need double quotes.

      Specimen Unit 1 Paper 01 (2021), Item 36. A program meant to print a string constant. Before looking at quotes and brackets, check that the program has a main function at all.

      When writing string code in an exam, always show the declaration with a size that allows for the terminator, use strcpy and strcmp rather than = and ==, and include string.h in a full program.

      More worked answers are on the CS Solutions page.

      Previous: Module 3 • Lesson 07 – Arrays in C: Storing Lists, Searching, Merging and Splitting. Next: Module 3 • Lesson 09 – Functions in C: Parameters, Return Values and Breaking Programs into Parts.

      Syllabus link: CAPE Computer Science (CXC A19/U2/21), Programming (Unit 1, Module 3). Specific Objective 6 (second part): use arrays in programs, including character arrays (strings).

      Video search terms

      Search YouTube for: "C strings null terminator", "strcpy strcat strcmp tutorial", "fgets vs scanf C".

      Try it 4Quick quiz

      Tap an answer. All eight questions are self-checks on this lesson.

      Updates

      2026/12/01

      - Updated the copyright line.

      2026/11/24

      - First version of the lesson.

      © 2026 islandclass.org

      Leave a Reply