7.4. String size

To find the size (or length) of a string (number of characters), we can use the size function. The syntax for calling this function is a little different from what we've seen before.

The active code below outputs the size of string fruit.

Finding the size of a string
 1#include <cstddef>
 2#include <iostream>
 3#include <string>
 4
 5using std::size_t;
 6
 7int main() {
 8    std::string fruit = "Watermelon";
 9    std::cout << fruit.size();
10}

Note

The string class does include a function length which does the same thing as size, but in general, we will use size mostly to be consistent with other container classes in the C++ Standard Library.

To describe this function call, we would say that we are invoking the size function on the string named fruit. This vocabulary may seem strange, but we will see many more examples where we invoke a function on an object. The syntax for function invocation is called “dot notation,” because the dot (period) separates the name of the object, fruit, from the name of the function, size.

size takes no arguments, as indicated by the empty parentheses (). The return value is an unsigned size type, which we store in std::size_t when a variable is needed. For "Watermelon", the size is 10. Include <cstddef> and use std::size_t in a complete program.

To find the last letter of a string, you might be tempted to try something like

char last = fruit[fruit.size()]; // The null terminator, not the last letter

Reading fruit[fruit.size()] gives the terminating null character. The characters of "Watermelon" have indices 0 through 9. For a nonempty string, the last character has index fruit.size() - 1.

Warning

Check that a string is not empty before subtracting 1 from its size. Sizes are unsigned, so subtracting 1 from zero wraps to a large value; it does not produce a valid character index.

The active code below outputs the last character in string fruit using the size function.

Finding the size of a string and outputting it
 1#include <cstddef>
 2#include <iostream>
 3#include <string>
 4
 5using std::size_t;
 6
 7int main() {
 8    std::string fruit = "Watermelon";
 9    if (!fruit.empty()) {
10        char last = fruit[fruit.size() - 1];
11        std::cout << last;
12    }
13}

Q1

What is printed by the following statements?

string s = "coding rocks";
cout << s.length() << '\n';

Q2

What is printed by the following statements?

string s = "coding rocks";
cout << (s[s.length()-5]) << '\n';

Q3

Construct a block of code that prints the number of characters in a string, with course being the first variable initialized.

  1. cout << num_chars << '\n';
  2. int main() {
  3. num_chars = course.size();
  4. num_chars = length(course); #distractor
  5. std::size_t num_chars;
  6. string course = "Programming";
  7. string num_chars; #distractor
  8. }