Problem Solving and Program Design in C (5th Edition) by Jeri R. Hanly and Elliot B. Koffman
CP 202 Chapter 9
Declaring String
A string in C is implemented as an array of char. Declaring a string variable is the same as declaring an array of char: char string_var[30];
Declaring and Initializing String
Initializing string variables: char str[10] = “Hello to”; It will look in the memory like: [0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
H
e
l
l
o
t
o \0
The str[8] contains the character ‘\0’, the null character, that marks the end of a string. This means that str can contain only 9 characters. If you want to work with an array of char as string, you need to add the null character at the end.
Arrays of String
An array of strings is a two-dimensional array of characters in which each row is one string. char month[12][10] = {“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”};
Strings and I/O Functions
You need to use the placeholder %s with the string variables.
char str[20] = “Hello to”;
char month[12][10] = {“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”}; printf(“%s\n”, str); hello to
printf(“ %c%c \n”, str[4], month[1][3]); or printf(“%s\n”, month[10]);
// // // November
Strings and I/O Functions EXAMPLE
Strings and I/O Functions EXAMPLE (OUTPUT)