The standard C++ library provides a string class type that supports string operations and manipulations. Unlike a standard character array, the string class can dynamically resize itself and supplies methods that help manipulate the string.
To instantiate and initialise a standard string object -
std::string str2 ("Hello String!");
or
const char* cStyleConstString = "This is a string";
std::string newString (cStyleConstString);
Instantiating a string object does not require the programmer to stipulate the length of the string or the memory allocation details because the constructor of the STL string class automatically does this.
The contents of an STL string can be accessed via iterators or via an array-like syntax using the subscript operator [] and offset. The following code sample lists all the characters in string mystring, one by one.
#include <string>
#include <iostream>
int main ()
{
using namespace std;
string myString ("Hello World"); // declare and initialise the string mystring
cout << "list elements in string using array-syntax: " << endl;
for (int charCounter = 0; charCounter < myString.length();++ charCounter) {
cout << "Character " << charCounter << " =";
cout << myString [charCounter] << endl;
}
cout << endl;
return 0;
}
A further demonstration of some string class methods
#include <string>
#include <iostream>
#include <algorithm>
int main ()
{
using namespace std;
string word="hello world";//create and initialise string word
cout << "Original sting-" << word<< endl;
transform(word.begin(), word.end(), word.begin(), ::toupper);//transform string word to upper case
cout << "uppercase sting-" << word << endl;
reverse (word.begin (), word.end ());//reverse characters in string word
cout << "reverse sting-" << word << endl;
reverse (word.begin (), word.end ());//reverse characters in string word
word.erase (5, 6);//erase final 6 letters in string word
cout << "erase first 5 characters-" << word << endl;
cout << "enter you name" << endl;
string usr_name;
cin >> usr_name;//input string value
word += " ";
word += usr_name;//add user name to word
cout << word <<endl;
return 0;
}
Last Updated: 15 September 2022