The string class in C++

In C++ a string is implemented as an instance of the string class. Inorder to use the functions of this class, the following include statement must be part of your program code:

#include <string>

As the string class is a member of the namespace  std , an instance of this class is declared with the following syntax:

std::string    messageStr; // declares a string called  messageStr

Remember, the std:: syntax can be omitted, provided you include  the following statement  in your code:

using namespace std;

The members of the string class are:

Parameters:

str a string    [(data type: string]

pos a (character) position in the string [ data type:  type_t ]

no the number of characters selected  [ data type: type_t ]

Commonly used methods in the string class, include:

length()        returns the number of characters in the stored string

capacity()   returns the capacity of the string; this is greater than or equal to the length of the string

[i]                   returns the ith character of the string

insert( pos, str )       inserts the string st, starting at the position pos in the string

remove( pos, no )      starting at position pos in the string, removes the number of characters  no

get_at( pos )                returns the character at position pos in the string

put_at( pos, char )    replaces the character at position pos, with the character char

replace( pos, no, str )    starting at position pos, replaces number of characters no, with the string str

+                  returns the concatenation of two strings,  eg    john + smith   would be  johnsmith

substr( pos, no )      returns a new string that begins with the character at position pos in the original string, and has length  no  (remember:     no  =  number of characters)

Strings in C++

Strings and Arrays of characters in C++

Low level strings are represented by arrays of characters in C and C++. These arrays are terminated by ‘\0′ , the special marker character null, which is used to indicate the end of a string.

char string1[ ] = { ‘H’,'e’,'l’,'l’,'o’,’ ‘, ‘W’, ‘o’, ‘r’, ‘l’, ‘d’, ‘\0′ }

The following short program could be used to display string1 :

#include <iostream>

using namespace std;

int main() {

char string1[ ] = { ‘H’,'e’,'l’,'l’,'o’,’ ‘, ‘W’, ‘o’, ‘r’, ‘l’, ‘d’, ‘\0′ } ;

cout << string1 << endl ;

return 0;

}

Using Enumerations in C++

Enumerations in C++ work in a similar manner to other languages, to restrict a particular variable to having a specific set of values.

For example:

enum Names {Fred, Mary, John, Anne}

In this case, a  new type is created, which may have <b>only</b> the values Fred, Mary, John, Anne.

The compiler will represent Fred as 0, Mary as 1  and so on. John will take the next value, which here will be 2.