5.12.2. The C++ Type string

This page is provided for your information. In this course, please limit yourself to basic null-terminated strings. Do not use type string.

Remember that part of the goal of this course is to learn how to do things at a very basic level without relying on a library that hides how things work.

Type string

The C++ library provides a type called string. To use it, #include <string>.

The memory occupied by strings is managed using reference counts. So you should not try to do your own memory management with them. They are deleted automatically.

Here is a partial list of operations available for type string. In all of these, assume that s and t have type string.

string s = (string) "null-terminated string";

The compiler will convert a null-terminated string to type string for you.


The length of string s.

s + t

The concatenation of s and t. For example,
  string s = "the cat "
  string t = "in the hat"
  string r = s + t;
makes r be string "the cat in the hat". Strings s and t are not changed.


This is the k-th character in string s (numbering from 0).

s == t

This is true if strings s and t have exactly the same characters, in the same order. So it is a sensible equality test for strings. You can also use comparisons such as < and > on strings. They compare using alphabetical order.


A value of type string has a null-terminated string as part of it information. s.c_str() yields a pointer to that null-terminated string. It does not copy the null-terminated string, and this pointer becomes a dangling pointer if string s becomes inaccessible. The system does not remember that you have a pointer (of type char*) to part of the string's information.