Monday, December 13, 2010

Strings 101 - Part III Exercises

The string length() method.

In the last exercise we learnt that if we have a string, s, we can obtain it's length by calling it's length() method. From now on, we'll use the word method when referring to a function that's a member of a class. In the previous lesson, getline(), is a method of the cin iostream class.

Example 1
    string s;
    int i;

    s = "this is a string";
    i = s.length();

In the example above, s is a string. The value of s is: this is a string.

In the second line, i is declared as an integer, a whole number. The statement: i = s.length() assigns the value of s.length() to the integer, i.

The value of i is therefore 16.

  1. Write a program that asks the user for their name, displays their name and the length of the name.
     
  2. Write a program that asks the user to type in two lines. Display both lines of text and then determine which one is longer, the first line typed in, or the second one.
     
  3. Write a program that asks the user to type in a single word. Change the word from a lower-case word to an upper-case word. Assuming the ASCII character set only, the lower-case 'a' is ASCII 97 and the upper-case 'A' is ASCII 65. The lower-case 'z' is ASCII 122 and the upper-case 'Z' is ASCII 90. An individual string letter can be referenced by it's index. If s is a string, then s[0] is the first letter in the string. s[1] is the second letter in the string, and so on.
     
  4. Write a program that reads a line of text from the user, encrypts the string by changing each letter in the string with the one immediately after it in the ASCII table. Lower-case 'a' is replaced by lower-case 'b'. Upper-case 'X' is replaced by upper-case 'Y'. and so on.

Possible solutions will be posted in a later lesson.

No comments:

Post a Comment