Length of a String
How many characters does a string have? sizeof isn't the answer: it gives the size of the whole array, including the '\0', and later in this lesson you'll see arrays that have more room than their text needs. C has a ready-made function for this. A function is a piece of code with a name that does one job. You use it by writing its name and, in parentheses, what it should work with. printf is a function too.
Functions for strings are in the library string.h. A library is a set of ready-made functions. To use them, include its header file at the top of the program, as you do with stdio.h for printf:
#include <stdio.h>
#include <string.h>
int main(void) {
char name[] = "Anna";
int length = strlen(name);
printf("%s has %d letters\n", name, length);
return 0;
}This prints:
Anna has 4 lettersThe function strlen (string length) counts the characters before the null character; the '\0' itself doesn't count. Spaces and punctuation marks are characters too, so "Hi, Tom!" has the length 8. If you forget #include <string.h>, the error message starts with call to undeclared library function 'strlen', and the note under it tells you which header file to include.
Why store the length in the variable length first? You may be tempted to put strlen straight into printf, but then the program doesn't compile:
char name[] = "Anna";
printf("%d\n", strlen(name));main.c:6:20: error: format specifies type 'int' but the argument has type '__size_t' (aka 'unsigned long') [-Werror,-Wformat]strlen gives its result as a different kind of whole number, size_t, which can't be negative, and %d is only for int. When you store the result in an int variable, it is converted to int, and %d fits. (Under the message, Clang suggests %zu, the format specifier for size_t. That works too.)
With the length, you can find the last character. It's at the index length - 1, because indexes start at 0. At the index length is the '\0':
char name[] = "Anna";
int length = strlen(name);
printf("Last letter: %c\n", name[length - 1]);This prints:
Last letter: aWatch out for letters with accents, such as é or ü. Text is stored in the UTF-8 encoding, and in it, such a letter takes two chars:
int length = strlen("café");
printf("%d\n", length);This prints:
5So the last char of "café" is only half of the é. You can print texts with accents without any problem, but write the strings you work with character by character without accents.
Instructions
Add #include <string.h> at the top of the program. Below the printf, store the length of city in an int variable length with strlen, and print it so that the output has the line Letters: 9.
Then print the last letter of the city, city[length - 1], with %c: Last letter: m.
Start programming for free
3/10