Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

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

  1. 1

    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");.

  2. 2

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

Back

4/10

  1. 1. Text in a Variable
  2. 2. Characters of a String
  3. 3. Length of a String
  4. 4. Going Through a String
  5. 5. Room in the Array
  6. 6. Joining Strings
  7. 7. Comparing Strings
  8. 8. Character Functions
  9. 9. Aligned Columns
  10. 10. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.