The string class in C++
By graemew on May 26, 2009 in Working with 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)
Sorry, comments for this entry are closed at this time.