Characters of a String
A string is an array, so each of its characters has an index, counted from 0 as in any array. name[0] is the first character. It has the type char, so you print it with %c:
char name[] = "Tina";
printf("%c\n", name[0]);
printf("%c\n", name[3]);This prints:
T
aThe last letter of "Tina" has the index 3, and at the index 4 is the null character. Print it as a number with %d, and you'll see it's really there:
printf("%d\n", name[4]);This prints:
0Don't mix up %s and %c: %s is for a whole string, %c for one character. With printf("%s\n", name[0]);, the program doesn't compile, and under the message, Clang even suggests the right format specifier, %c:
char name[] = "Tina";
printf("%s\n", name[0]);main.c:5:20: error: format specifies type 'char *' but the argument has type 'char' [-Werror,-Wformat]You can also change a character. Assign a new one to an element, as with any array:
char name[] = "Tina";
name[0] = 'N';
printf("%s\n", name);This prints:
NinaThe new character goes in single quotes. name[0] = "N"; would put a whole string where one character belongs, and you'd get the error about char[2] from the previous exercise.
Single quotes matter in conditions too. To check the first letter, write if (name[0] == 'N'). With double quotes, if (name[0] == "N"), the program compiles here, but the condition is never true, because you are comparing one character with a whole string. Clang warns about it, but this site doesn't show warnings, so you'd only see that the program doesn't do what it should.
The size of the array stays the same. "Tina" has room for 4 letters and the '\0', so name[5] = 's'; is past the end of the array, and the program doesn't compile. You'll see how to make room for a longer text later in this lesson.
Instructions
Print the first and the last character of word on one line, separated by a space, with %c. The output should have the line m e.
Below that, change the first character of word to 'h' and print the whole word again with %s: house.
Start programming for free
2/10