Characters
In the Strings lesson, name[0] gave you one character of a string. If the index is a loop variable, you can visit every character, one after the other. This is how you count the vowels in a word or check a password.
#include <iostream>
#include <string>
using namespace std;
int main() {
string word = "cat";
for (int i = 0; i < word.length(); i++) {
cout << i << ": " << word[i] << "\n";
}
return 0;
}
Output:
0: c
1: a
2: t
The loop is the same as the array loops from the Arrays lesson. The only difference is the limit: it is word.length(), so the same loop works for a word of any length. Each word[i] is a char.
What kind of character is it?
The header <cctype> has small functions that check one character. To use them, add #include <cctype> at the top. Each one answers a yes or no question:
| Function | Is the character... |
|---|---|
isalpha(c) | a letter, a to z or A to Z? |
isdigit(c) | a digit, 0 to 9? |
isupper(c) | a capital letter? |
With them, counting the kinds of characters is a loop and an if:
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
string code = "Room 42B!";
int letters = 0;
int digits = 0;
for (int i = 0; i < code.length(); i++) {
if (isalpha(code[i])) {
letters++;
} else if (isdigit(code[i])) {
digits++;
}
}
cout << "Letters: " << letters << "\n";
cout << "Digits: " << digits << "\n";
return 0;
}
Output:
Letters: 5
Digits: 2
R, o, o, m and B are letters, and 4 and 2 are digits. The space and the ! are neither, so they are not counted.
These functions do not return true or false. They return a number: 0 means "no", and any other number means "yes". The exact number depends on the system, and it is not always 1. Here is what they returned when we ran them:
cout << isalpha('b') << "\n";
cout << isupper('B') << "\n";
cout << isupper('b') << "\n";
Output:
1024
256
0
An if treats every number except 0 as true, so if (isalpha(c)) works. But if (isalpha(c) == 1) would be false for the letter b. Never compare the result with 1.
Changing case
toupper(c) gives the capital form of a letter, and tolower(c) gives the small form. Like the functions above, they return a number, not a char. If you print the result directly, you see the character code from the Type Conversion lesson:
cout << toupper('a') << "\n";
Output:
65
To get the letter, store the result in a char variable first:
char big = toupper('a');
cout << big << "\n";
Output:
A
Storing it back into the string works the same way, because each word[i] is a char. This loop changes a whole string to capital letters:
string code = "Room 42b!";
for (int i = 0; i < code.length(); i++) {
code[i] = toupper(code[i]);
}
cout << code << "\n";
Output:
ROOM 42B!
toupper gives back any character that is not a small letter without changing it. That is why the digits, the space and the ! stay the same.
In the exercise, count the letters and the digits in a line of text, and change the line to capital letters.