Chapter 15 Strings

15.1  String Variables

A string is a group of characters such as "Hello" or "I am 21 today".  Strings are enclosed in double quotes unlike character variables which are enclosed in single quotes.  Strings are a class that store the data in character arrays.  For some compilers you must include the string library at the top of your program:   #include <string>

The following program shows how to declare a variable of type string, assign it a value (Hello World!), and print it out.

Program 15.1a Declaring and Using a String

#include <iostream>
using namespace std;
int main()
{
   string A = "Hello World!";
   cout << A << endl;
   return 0;
}

Output
Hello World!

The next program shows how strings can be concatenated (joined together) using the plus sign.  Notice how a space between the two words was included by placing it in the double quotes " ".

Program 15.1b - Concatenating Strings

#include <iostream>
using namespace std;
int main()
{
   string A = "Hello";
   string B = "World";
   string C = A + " " + B + "!";
   cout << C << endl;
   return 0;
}

Output
Hello World!

Strings can be compared.  The next program compares "apple" to "apricot" to see which one is greater.  When comparing strings, the ASCII number for each letter is compared (refer to the ASCII chart).  Try running the same program with "Apricot" capitalized.

Program 15.1c - Comparing Strings

#include <iostream>
using namespace std;
int main()
{
   string A = "apple";
   string B = "apricot";
   if (A < B)
      cout << A << " is less than " << B << endl;
   else
      cout << A << " is greater than " << B << endl;
   return 0;
}

Output
apple is less than apricot

15.2  String Functions

When you include the string library at the top of your program, you also have access to many functions that allow you to work with strings.  Example functions include the ability to search a string for a letter or letters, the ability to insert text within a string, and the ability to print a portion of a string.  The string type is actually a class and its functions are actually called methods.  Classes and methods are discussed in later chapters.   

Size

The size function allows you to count the total number of characters in a string.  Remember to count spaces.  The following program demonstrates this function.

Program 15.2a - String Size

#include <iostream>
using namespace std;
int main()
{
   string A = "Hello World!";
   cout << A.size() << endl;
   return 0;
}

Output
12

All the string functions are called by placing a period after the string variable name followed by the function name (size).  After the function name, are open and close parentheses.  With the size function, there are no parameters.  With most other string functions, however, there will be parameters to send the function.

Substring

The substring (substr) function is used to return a portion of a string.  This function requires two parameters (1) the starting position, and (2) the number of characters.  Important - When you are referring to the position of a character in a string, the first character is at position zero.  When you are referring to the number of characters in strings, always begin counting with one.  Look at the string definition below.

string S1 = "This sentence used to demonstrate substrings";

The table below shows various substring commands using S1 and what they return.

Substring Examples

Substring Command What it Returns
S1.substr(0,1) "T"
S1.substr(0,4) "This"
S1.substr(14,3) "use"
S1.substr(1,2) "hi"

The program below demonstrates use of the substring function.

Program 15.2b - Substring Function

#include <iostream>
using namespace std;
int main()
{
   string S1 = "0123456789";
   string S2 = "good morning";
   cout << "Today I am " << S1.substr(2,2) << " years old.\n";
   cout << "You are a " << S2.substr(0,4) << " neighbor.\n";
   return 0;
}

Output
Today I am 23 years old.
You are a good neighbor.

Insert

The insert function is used to insert text at any position in a string.  Unlike the substring function, when you use the insert function, the value of the string is changed.  This function takes two parameters - the position where the insert will be made, and the text to be inserted.  The text is inserted before the text at the specified position.  The following program demonstrates the string insert function.

Program 15.2c - Insert Function

#include <iostream>
return 0;

int main()
{
   string X = "happy birthday";
   cout << X.insert(0,"have a ") << endl;
   string Y = "very ";
   X.insert(7,Y);
   cout << X << endl;
   return 0;
}

Output
have a happy birthday
have a very happy birthday

Replace

The replace function is used to replace a portion of a string with another string.  As with insert, when you use the replace function, the value of the string is changed.  This function takes three parameters - the position where the replace will be made, the number of characters to replace, and the text to replace it with.  The following program demonstrates the replace function.

Program 15.2d - Replace Function

#include <iostream>
using namespace std;

main()
{
   string X = "It is time for class";
   X.replace(11, 3, "to go to");
   cout << X << endl;
   X.replace(3, 2, "will be");
   cout << X << endl;
   return 0;
}

Output
It is time to go to class
It will be time to go to class

Find

The find function is used to search for character(s) within a string.  It takes two parameters - the character(s) to search for and the position where to begin the search.  The function returns an integer that corresponds to the starting position of where the character(s) were found.  Observe the following string definistion:

string Z = "It is time for class.";

The table below shows various find commands using the above string definition.  Notice that the last example searches for the letter "q" which is not contained in the string Z.  When the search string is not found, the find function returns the largest number an integer can be: 4294967295.

Find Examples

Substring Command What it Returns
Z.find("i", 0) 3

Z.find("me", 0)

8

Z.find("i", 4)

7

Z.find("q", 0)

4294967295

The program below demonstrates a search and replace program.  It searches for any spaces in the string A and replaces them with a dash.  The while loop executes as long as the find statement returns a value less than the length of A.

Program 15.2e Search and Replace

#include <iostream>
using namespace std;

int main()
{
   string A = "This is a search and replace example";
   int X = A.find(" ", 0);
   while (X < A.size())
   {
      A.replace(X,1,"-");
      X = A.find(" ", X+1);
   }
   cout << A << endl;
   return 0;
}

Output
This-is-a-search-and-replace-example


 

Exercises Chapter 15

Given the following string definition, what will each of the cout statements print?

string Z = "abcdefghijklmnopqrstuvwxyz";

1. cout << Z[0] << Z[1] << Z[2];

2. cout << Z[25] << Z[24] << Z[23];

3. cout << Z[7] << Z[8];

4. cout << Z[19] << Z[4] << Z[23] << Z[0] << Z[18];

What will the following cout statements print?

#include <iostream.h>
#include <string>

int main()
{
  string A = "good morning";
  string B = "alphabet soup";

  cout << B[0] << B[1] << B[2];

  cout << A.substr(0,4) << B.substr(9,4);

  cout << A.substr(5,3) << B[6];

  A.replace(5,3,"eve");

  cout << A;

  cout << A.find("e",0);

  cout << B.substr(0,5);

  A.insert(0,"very ");

  cout << A;

  return 0;
}

 

 

 

 

5. (a) goo   (b) mor   (c) alp

6. (a) goodsoup   (b) good soup

7. (a) mornbe  (b) more  (c) mor

 

8. (a) good evening  (b) good eve

9. (a) e  (b) 5  (c) v  (d) 7

10. (a) alpha  (b) good  (c) bet

 

11. (a) very alpha
    (b) very good morning
    (c) very good evening

 

Given the following string definition, what do the functions return?

string Alpha = "it is rainy today", Beta = "it isn't sunny";

12. Alpha.size()                   17. Alpha.find("i",1)

13. Beta.size()                    18. Alpha.find("to",0)

14. Alpha.substr(6,4)              19. Beta.find("nn",10)

15. Beta.substr(9,3)               20. Beta.find("z",0)

16. Alpha.find("i",0)