The C++Course provides a general introduction to programming in C++. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.


Length

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

  int length;
  length = fruit.length();

To describe this function call, we would say that we are invoking the length 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, length.

length takes no arguments, as indicated by the empty parentheses (). The return value is an integer, in this case 6. Notice that it is legal to have a variable with the same name as a function.

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

  int length = fruit.length();
  char last = fruit[length];       // WRONG!!

That won't work. The reason is that there is no 6th letter in "banana". Since we started counting at 0, the 6 letters are numbered from 0 to 5. To get the last character, you have to subtract 1 from length.

  int length = fruit.length();
  char last = fruit[length-1];


Last Update: 2005-12-05