Going Through a String

To do something with every character of a string, such as count certain letters or look for a digit, go through it in a loop, just like through an array of numbers. There's one difference: with a string, you don't need to know its length. The loop can stop at the null character:

char word[] = "Hello";
for (int i = 0; word[i] != '\0'; i++) {
    printf("%c\n", word[i]);
}

This prints:

H
e
l
l
o

Read the condition as “while the character at the index i isn't the end of the text”. In the first pass through the loop, i is 0 and word[0] is 'H'. After the fifth pass, i is 5, word[5] is '\0', and the loop ends.

You can also write the loop with strlen, like a loop over an array with a count. Both ways are right:

char word[] = "Hello";
int length = strlen(word);
for (int i = 0; i < length; i++) {
    printf("%c ", word[i]);
}
printf("\n");

This prints:

H e l l o

Inside the loop, word[i] is one character, so you can test it with an if. This loop counts the letters l, with the same counting pattern as in the lesson on arrays:

char word[] = "Hello";
int count = 0;
for (int i = 0; word[i] != '\0'; i++) {
    if (word[i] == 'l') {
        count++;
    }
}
printf("l appears %d times\n", count);

This prints:

l appears 2 times

Watch out for two things. Compare a character in single quotes: with the condition word[i] == "l", the program compiles here, but the condition is never true, and the count stays 0. And uppercase and lowercase letters are different characters: 'H' == 'h' is false, so a loop that counts 'h' finds nothing in "Hello".

Instructions

Go through word with a for loop and print its characters on one line, each followed by a space: M i s s i s s i p p i. End the line after the loop with printf("\n");.

Below that, count how many times the letter s is in the word, and print s appears 4 times.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

4/10