A string is an array of characters
C has no special text type. A piece of text – a string – is simply an array of chars:
#include <stdio.h>
int main() {
char name[20] = "Asha";
printf("Hello, %s!\n", name);
printf("First letter: %c\n", name[0]);
return 0;
}Output
Hello, Asha! First letter: A
char name[20]makes room for up to 20 characters.%sprints a whole string.name[0]is one character, so we print it with%c.
The hidden '\0' at the end
How does printf know where the text stops? C puts a special invisible character at the end of every string: '\0', called the null character. So "Asha" really takes 5 places:
| Index | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| Character | 'A' | 's' | 'h' | 'a' | '\0' |
Think of it like this:
'\0'is like the full stop at the end of a sentence. It tells everyone reading: "the text ends here".
Remember: A string needs one extra place for
'\0'. To store a word of 10 letters, the array needs at least 11 places.
Changing letters
Because a string is an array, you can change single letters:
#include <stdio.h>
int main() {
char word[10] = "cat";
word[0] = 'b';
printf("%s\n", word);
return 0;
}Output
bat
Reading a word
scanf with %s reads one word. Notice: no & here! An array name already tells scanf where the memory is.
#include <stdio.h>
int main() {
char city[30];
printf("Where do you live? ");
scanf("%s", city);
printf("\n%s is a nice place!\n", city);
return 0;
}Input (what the user types)
Mumbai
Output
Where do you live? Mumbai is a nice place!
Common mistake:
scanf("%s", ...)stops at the first space. If the user typesNew York, you only getNew. The last lesson of this module shows how to read a whole line.