The C++ string class

Standard C++ provides a special data type for storing and working with strings. Because a char variable can store only one character in its memory location, another data type is needed for a variable able to hold an entire string. Although C++ does not have a built-in data type able to do this, standard C++ provides something called the string class that allows the programmer to create a string type variable.

Strings, which are a series of characters stored in consecutive memory locations, can be virtually any length. This means that there must be some way for the program to know how long a string is. In C++, an extra byte is appended to the end of string literals when they are stored in memory. In this last byte, the number 0 is stored. It is called the null terminator or null characters, and it marks the end of the string.

String declaration and assignment


stringExample.cpp

★ The difference between string literals and char literals

NOTE:
  1. To use strings, you must include a header file <string> in the source code.
  2. String literals are enclosed in double quotation marks.
  3. C++ automatically places the null terminator at the end of string literals

Manipulationg String Data

★ String Concatenation


stringConcatenation.cpp

★ String Length

To get the length of a string, use the length() function.

stringLength.cpp

Length of fullName
A d a   L o v e l a c e \0
12 bytes

★ Substring in C++

In C++, substr() is a predefined function used for string handling. This function takes two values pos and len as an argument and returns a new string object.

subString.cpp

Character A d a   L o v e l a c e \0
Position 0 1 2 3 4 5 6 7 8 9 10 11

★ String find in C++

In C++, find() is a predefined function to find the starting position of one string in the specified string. It returns the index of the first occurrence of the substring in the string from given starting position. The default value of starting position is 0. If no matches were found, the function returns string::npos.

stringfind.cpp