Container for storing elements of type char

View versions (1)

Definition

The std::string class template is defined in the standard header <string>, and in the nonstandard backward-compatibility header <string.h>.

namespace std {
            typedef basic_string<char> string;
}

Description

The class template basic_string stores and manipulates sequences of type char. std::string is an STL container which is part of basic_string for storing elements of type char.

Member Functions

OperationDescription
constructorCreate or copy a string
destructorDestroys a string
=, assign()Assign a new value
swap()Swaps values between two strings
+=, append(), push_back()Append characters
insert()Inserts characters
erase()Deletes characters
resize()Changes the number of characters (deletes or appends characters at the end)
replace()Replaces characters
+Concatenates strings
==, !=, <, <=, >, >=, compare()Compare strings
size(), length()Return the number of characters
max_size()Returns the maximum possible number of characters
empty()Returns if the string is empty
capacity()Returns the number of characters that can held without be reallocation
[], at()Access a character
>>, getline()Read the value from a stream
<<Writes the value to a stream
copy()Copies or writes the contents to a C-string
c_str()Returns the value as C-string
data()Returns the value as character array
substr()Returns a certain substring
get_allocator()Returns the allocator

Iterators

OperationDescription
begin(), cbegin()Returns an iterator to the beginning
end(), cend()Returns an iterator to the end
rbegin(), crbegin()Returns a reverse iterator to the beginning
rend(), crend()Returns a reverse iterator to the end

Search

OperationDescription
find()Find characters in the string
rfind()Find the last occurrence of a substring
find_first_of()Find first occurrence of characters
find_first_not_ofFind first absence of characters
find_last_ofFind last occurrence of characters
find_last_not_ofFind last absence of characters

Numeric conversions

OperationDescription
stoi(), stol(), stoll()Converts a string to an signed integer
stoul(), stoull()Converts a string to an unsigned integer
stof(), stod(), stold()Converts a string to an floating point value
to_string()Converts an integral or floating point value to string
to_wstring()Converts an integral or floating point value to wstring

References

Example 1
Problem

This simple program shows how to read and how to print out a string.

Workings
#include <iostream>
#include <string>

using namespace std;

int main()
{
    // Enter text into a string
    string qWord;
    cout << "Enter a word: ";
    cin >> qWord;
    cout << "The word is: " << qWord << endl;

    return 0;
}
Solution

Output:

Enter a word: Hello!
The word is: Hello!

References