מחרוזות ותווים
מחרוזת ב־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";| index | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| 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.
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;
}ADC12The 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.
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: 10strlen 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.)
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 charactersfgets(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.
Four functions from string.h
These functions need #include <string.h>. Every one of them walks the strings until '\0'.
| Function | Job | Example | Result |
|---|---|---|---|
strlen(text) | count the visible characters | strlen("ADC12") | 5 |
strcmp(a, b) | compare two strings | strcmp("ADC", "ADC") | 0, which means equal |
strcpy(dst, src) | copy src into dst | strcpy(label, "ADC") | label holds "ADC" |
strcat(dst, src) | append src to the end of dst | strcat(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.
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 1The 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.
Key words
| English | Hebrew | Meaning |
|---|---|---|
| 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.