First Next Previous Last Glossary About

An introduction to strings


Introduction

If you have ever programmed in TurboPascal or FreePascal you would have discovered that dealing with strings was quite straightforward. Pascal gave you a string data type and a number of procedures and functions for dealing with strings.

In C and early C++ the situation was quite the opposite - strings were a terror to deal with and required you understand character arrays and pointers before using strings.

In later C++ standards the situation is quite different from C and early C++, it is very much like Pascal. C++ now provides a very powerful string class which makes dealing with strings quite delightful.

Although you probably won't do any work with classes in these early days it doesn't hurt to have some understanding of what a class is.


An introduction to the class

The class lies at the very heart of object-oriented programming and we look at it in detail later in this course. But, for now, there is no avoiding using classes, especially when we deal with strings and streams.

I may have written earlier that two of the advantages of C++ over C were the string class and the use of streams. The string class is an example of what really sets C++ apart from C. A class is a structure, sometimes called an ADT (Abstract Data Type) that encapsulates the data structures and the methods (ie the functions) that are used to operate on the data structures.

Imagine you have a structure called Person which encapsulates the attributes of a human being. The Person class contains data fields that can store values about attributes like age and height. The Person class can also contain methods that are appropriate to a human being. A human being can grow for example and can age.

Person.grow(1)    : tell the Person to grow by one centimetre
Person.age(1)     : tell the Person to age by one day.

We can refer to the methods in this way:

We have an object called Person and the object has methods (aka member functions) which define how the object behaves.

The string class follows the same model. There is a class called string and we can declare instances of this class - variables if you like.

#include <iostream>
#include <string>

void main()
{ string
   stringOne("Hello World"), //init
   stringTwo(stringOne),     //init
   stringThree;              //empty
   int i;

   stringTwo.append(" Again.");

   cout << stringOne
        << endl;
   cout << stringTwo
        << endl;
   cout << stringOne + " "
                 + stringTwo 
        << endl;
   cout << "Enter your name: ";
   cin >> stringThree;
   cout << "Hello "
        << stringThree 
        << endl;
}

The example program here shows a number of the features of the string class in C++.

There are many other things which can be done with strings but for now we will limit ourselves to a few basic operations. The string class is very powerful and the few string operations shown here just touch the surface. Even the methods shown here have many variations on them.


Return to top of page

Declaring strings

string m,n,o,p;

To use the string data type, ie the string class. This example declares four instances of string class:


Assigning values to strings

m = "David";
n = "and";
o = "Goliath";

The simplest way is to use the assignment operator to assign string constants to string instances.


string
   stringOne("Hello World"),
   stringTwo(stringOne); 

but you can also initialise a string when you declare it:


Return to top of page

Concatenating strings

The simplest way is to use the + operator:

p = m + " " + n + " " + o;

but you can also use the append method:

p.append(" meet for the last time!");


//strings_1.cc
#include <iostream>
#include <string>

int main()
{
 string k,m,n,o,p;

 m = "David";
 n = "and";
 o = "Goliath";

 k.assign("Solomon");
 cout << k
      << endl;

 cout << m << " "
      << n << " "
      << o << endl;

 p = m + " " + n + " " + o;
 cout << p << endl;

 p.append(" meet at last!");
 cout << p << endl;
 
 return 0;
}

The example strings_1.cc shows how to use string assignment and concatenation.

The assignment uses both the = operator and the assign() method.

The concatenation uses both the + operator and the append() method.

This example produces the output:

 Solomon
 David and Goliath
 David and Goliath
 David and Goliath meet at last!


Return to top of page

Copying a substring to a string

The substr() method requires two arguments, the first is the starting position of the substring in the host string, the second is the length of the substring.

string = string.substr(int start position, int length)

if we had the host string "Beware the ides of March" and wanted to copy the substring "ides" then the start position would be 11 and the length 4.

//ex27.cc
#include <iostream>
#include <string>

void main()
{ string m,n,o,p;
//these have not been initialised to any
//specific value except the empty string
//value.

  m = "Beware the ides of March";
  n = m.substr(11,4);
  o = m.substr(19);
  p = m.substr(16);
  cout << m << endl;
  cout << n << endl;
  cout << o << endl;
  cout << p << endl;
}

If the end position is left out then the substr method assumes that end position is the end of the string.

This example produces the output:

 Beware the ides of March
 ides
 March
 of March


Return to top of page

Inserting a string in a string

string.insert(int position, string)

The insert() method has two arguments, the first argument is a position at which to insert a string, the second argument is the string to be inserted.


//ex28.cc
#include <iostream>
#include <string>

void main()
{ string m,n,o,p;

  m = "Beware the ides of March";
  n = "Jeremy";
  m.insert(0,n);
  cout << m << endl;
  m = "Beware the ides of March";
  m.insert(0, n + ", "); 
  cout << m << endl;
}

This example produces the output:

 JeremyBeware the ides of March
 Jeremy, Beware the ides of March

in this example I have inserted strings at position 0 but you could insert at any location in the string.



Return to top of page

Replacing a substring in a string

string.replace(int start, int length, string)

The replace() method has three arguments, the first argument is a position at which the string to be replaced starts, the second argument is the length of the string to be replaced and the third argument is the replacement string.


//ex29.cc
#include <iostream>
#include <string>

void main()
{ string m,n;

  m = "Beware the ides of March";
  cout << m << endl;
  n = "September";
  m.replace(19,5,n);
  cout << m << endl;
}

This example produces the output:

 Beware the ides of March
 Beware the ides of September


Return to top of page

String size

//ex29a.cc
#include <iostream>
#include <string>

void main()
{ string m,n;
  int where, size;

  m = "Beware the ides of March";
  where = m.size();
  n = "April";
  size = n.size();
  cout << "Size of m is "
       <<  m
       << endl
       << "Size of n is "
       <<  n
       << endl;
}

The string.size() method returns the size of a string.

This example produces the output:

Size of m is 24
Size of n is 5


Return to top of page

Finding strings within strings

there is another useful method called find().

  string.find(String_to_find, start position in host string);

the find() method has two arguments. The first argument is the "key" string, i.e. the string we are trying to find in the host string. The second argument is the position at which the search should start. If you are searching the whole string then the second argument would be 0.

In the following example I used the find and size methods to determine the position where a replace should begin and how far the replace should extend.

//ex30.cc
#include <iostream>
#include <string>

void main()
{ string m,n,o,p;
  int where, size;

  m = "Beware the ides of March";
  where = m.find("March",0);
  n = "April";
  size = n.size();
  if (where != string::npos)
   { m.replace(where,size,n);
     cout << m << endl;
   }
  else cout << "Nothing to replace"
            << endl;

  where = m.find("March",0);
  if (where != string::npos)
   { m.replace(where,size,n);
     cout << m << endl;
   }
  else cout << "Nothing to replace"
            << endl;
}

It is a good idea to check that the string you want to replace is actually there. Before doing the replace, this example uses the find method to determine if the string we want to replace is embedded in the host string. The find method returns an integer which indicates where the queried string starts in the host string.

The condition

(where != string::npos)

indicates whether or not the word "March" occurred anywhere in m.




as I said earlier there is much more we can do with strings in C++ but you have enough to get going.

in this lesson you learned how to:

Return to top of page


Tutorial

i have combined the strings tutorial work with the work in the next topic which introduces files. You should read that topic and try the tutorial work there.

if you want some practice with strings then try the various examples from this page.

The ANSI C++ specification for the string class

ANSI strings library. This is a useful, if complex, reference. Even though it is complex you will find, with careful reading, that you can glean quite a bit from it. You can see the recommended declarations for all of the string class members and definitions of their meanings.


First Next Previous Last Glossary About


Copyright © 1999 - 2001 David Beech