Summary

In this lesson, you learned that:

  • A string is an array of characters (char) that ends with the null character '\0'. char name[] = "Anna"; has 5 elements: 4 letters and the '\0'. char name[20] = "Anna"; leaves room for a longer text.
  • 'A' is one character, "A" is a string of two characters ('A' and '\0').
  • A string is printed with %s: printf("%s\n", name);, never printf(name);. One character, such as name[0], is printed with %c.
  • You read and change characters through their index: name[0] = 'H';. You go through a string in a loop until the '\0': for (int i = 0; name[i] != '\0'; i++).
  • The library string.h has functions for strings: strlen gives the length without the '\0' (store it in an int: int length = strlen(name);), strcpy(target, text) copies a text into an array, and strcat(target, text) adds it to the end. The array must have room for the text and the '\0'.
  • Strings can't be assigned with = or compared with ==. strcmp(a, b) gives 0 for the same text, a negative number when a comes first in alphabetical order, and a positive one when it comes after b.
  • The library ctype.h works with characters: toupper and tolower give a changed character (you have to store it), and isupper, isalpha and isdigit answer with 0 (no) or another number (yes).
  • A width lines up columns: %-10s, %5d, %6.2f.
  • Letters with accents take two chars, so write the strings you work with character by character without accents.

In the next lesson, on functions, you'll learn to write your own functions, like strlen or toupper, and give names to the parts of your programs. But first, try out what you know on a password check.

Instructions

Go through password in a loop and count its digits and its uppercase letters. Print them as Digits: 4, uppercase: 1.

A password is strong when it has at least 8 characters, at least one digit and at least one uppercase letter. Check all three in one condition, with strlen and your counts, and print Strong password or Weak password. (When it works, try changing the password to "lion".)

Start programming for free

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

Or sign up with:

10/10