90 דק׳

מחרוזות ותווים

מחרוזת ב־C היא מערך של char שמסתיים בתו סיום: גודל המערך, מעבר עד הסוף, אורך מול גודל, קריאת שורה עם fgets, הפונקציות strlen, strcmp, strcpy ו־strcat, ומיון תווים (ניסוי מעבדה 16).

למצגתלקריאה באתרבאנגלית בלבד

השיעור הזה כתוב באנגלית בלבד.

A string is a char array

Text in C is stored in an array of char. Each element holds one character (תו). A string (מחרוזת) is such an array with one extra element at the end: the null terminator '\0' (תו סיום), which marks where the text ends.

char word[] = "CODE";
index01234
value'C''O''D''E''\0'

The compiler counts the characters of "CODE" and adds the '\0' by itself. Four visible characters need five elements. Every function that works with strings walks the array until it finds '\0'; without it, it would keep reading past the end of the array.

Do not confuse two characters that look alike:

  • '0' is the digit zero, a visible character (its code is 48).
  • '\0' is the value 0, the end of the string.
The four letters drop into their cells, then the null terminator, drawn dark, closes the string.לפתיחה במסך מלא

Capacity

The capacity (גודל המערך) is the number of elements in the array. It must be at least the number of visible characters plus one. "SENSOR" has 6 letters, so it needs 7 elements.

char name[4] = "NODE";   /* wrong: no room for '\0' */
char name[5] = "NODE";   /* right */
char name[] = "NODE";    /* right: the compiler counts 5 */

Walking a string

A number array is walked until the length. A string carries its own end marker, so it is walked until '\0':

#include <stdio.h>
 
int main(void)
{
    char text[] = "ADC12";
 
    for (int i = 0; text[i] != '\0'; i++) {
        putchar(text[i]);
    }
    putchar('\n');
 
    return 0;
}
ADC12

The condition is checked before every character. At index 5 the character is '\0', the condition is false, and the loop ends. putchar prints one character.

One click per character: the condition, the pointer and the console move together. The last click reaches '\0' and the loop stops.לפתיחה במסך מלא

Length and capacity

The length (אורך המחרוזת) of a string is the number of visible characters before '\0'. Counting them is a loop that walks to the terminator:

#include <stdio.h>
#include <string.h>
 
int main(void)
{
    char label[10] = "ADC12";
    int length = 0;
 
    while (label[length] != '\0') {
        length++;
    }
 
    printf("counted: %d\n", length);
    printf("strlen:  %d\n", (int)strlen(label));
    printf("sizeof:  %d\n", (int)sizeof label);
 
    return 0;
}
counted: 5
strlen:  5
sizeof:  10

strlen does the same count for you: 5, not counting '\0'. sizeof label is the capacity of the array: 10. A string can be shorter than its array; the elements after '\0' are simply not used. (strlen returns a size_t; the (int) cast lets us print it with %d.)

The counter walks the label until '\0'. The cells after the terminator are part of the array but not of the string.לפתיחה במסך מלא

Reading a line: scanf or fgets

scanf("%s", label) reads one word: it stops at the first space. If the user types Main sensor 2, the label holds only Main, and sensor 2 stays waiting in the input for the next read.

fgets reads a whole line, spaces included, and never writes more than the capacity:

#include <stdio.h>
#include <string.h>
 
int main(void)
{
    char label[32];
 
    printf("Label: ");
    if (fgets(label, sizeof label, stdin) == NULL) {
        return 1;
    }
    label[strcspn(label, "\n")] = '\0';
 
    printf("[%s] has %d characters\n", label, (int)strlen(label));
 
    return 0;
}
Label: Main sensor 2
[Main sensor 2] has 13 characters

fgets(label, sizeof label, stdin) stores at most 31 characters plus '\0'. It keeps the newline '\n' from the Enter key. strcspn(label, "\n") gives the index of the first '\n' (here 13), and writing '\0' there removes it. If the user only presses Ctrl+Z (end of input), fgets returns NULL and the program stops.

fgets fills the cells including the newline; strcspn finds it at index 13 and '\0' replaces it.לפתיחה במסך מלא

Four functions from string.h

These functions need #include <string.h>. Every one of them walks the strings until '\0'.

FunctionJobExampleResult
strlen(text)count the visible charactersstrlen("ADC12")5
strcmp(a, b)compare two stringsstrcmp("ADC", "ADC")0, which means equal
strcpy(dst, src)copy src into dststrcpy(label, "ADC")label holds "ADC"
strcat(dst, src)append src to the end of dststrcat(label, "-7")label holds "ADC-7"

strcmp returns 0 when the strings are equal, so the test for "equal" is strcmp(a, b) == 0. You cannot compare strings with ==: that compares where the arrays are in memory, not their characters.

strcpy, then strcat, then an append that does not fit: the last two characters land outside the array.לפתיחה במסך מלא

Classifying characters (lab experiment 16)

Lab experiment 16: read a string of up to 30 characters and count the uppercase letters, lowercase letters, digits, and everything else (the lab calls the last group "white"). The functions isupper, islower and isdigit from <ctype.h> test one character each.

#define _CRT_SECURE_NO_WARNINGS
#include <ctype.h>
#include <stdio.h>
 
#define CAPACITY 32
 
int main(void)
{
    char text[CAPACITY];
    int upper = 0, lower = 0, digit = 0, other = 0;
 
    if (fgets(text, sizeof text, stdin) == NULL) {
        return 1;
    }
 
    for (int i = 0; text[i] != '\0' && text[i] != '\n'; i++) {
        unsigned char c = (unsigned char)text[i];
        if (isupper(c)) {
            upper++;
        } else if (islower(c)) {
            lower++;
        } else if (isdigit(c)) {
            digit++;
        } else {
            other++;
        }
    }
 
    printf("UPPER %d\n", upper);
    printf("LOWER %d\n", lower);
    printf("DIGIT %d\n", digit);
    printf("OTHER %d\n", other);
 
    return 0;
}
ADC-7
UPPER 3
LOWER 0
DIGIT 1
OTHER 1

The loop stops at '\0' or at the newline, so the Enter key is not counted. The cast to unsigned char keeps the ctype.h functions safe for every character value. A space is counted as "other". With the input node 2 the output is UPPER 0, LOWER 4, DIGIT 1, OTHER 1.

Type any label: the cells, the length and the four counts update as you type. Try an empty label, only spaces, and 30 characters.לפתיחה במסך מלא

Key words

EnglishHebrewMeaning
stringמחרוזתa char array that ends with '\0'
character (char)תוone letter, digit or symbol
null terminator '\0'תו סיוםthe value 0 that marks the end of a string
capacityגודל המערךthe number of elements in the array
lengthאורך המחרוזתthe visible characters before '\0', strlen
newline '\n'ירידת שורהthe Enter key; fgets keeps it
uppercase, lowercaseאות גדולה, אות קטנהisupper, islower
digitספרהisdigit
whitespaceרווחspace, tab, newline
copy, append, compareהעתקה, שרשור, השוואהstrcpy, strcat, strcmp

Practice

More questions, with answers: Practice: traversal and strings, questions 31 to 34 and 40 to 44.