Character access
There are two almost identical ways to access characters in a string. The easier to use and faster version is the overloaded operator[]:
char& string::operator[] (size_type nIndex) const char& string::operator[] (size_type nIndex) const
Sample code: Output: f abcdeXg |
There is also a non-operator version. This version is slower since it uses exceptions to check if the nIndex is valid. If you are not sure whether nIndex is valid, you should use this version to access the array:
char& string::at (size_type nIndex) const char& string::at (size_type nIndex) const
Sample code: Output: f abcdeXg |
Conversion to C-style arrays
Many functions (including all C functions) expect strings to be formatted as C-style strings rather than std::string. For this reason, std::string provides 3 different ways to convert std::string to C-style strings.
const char* string::c_str () const
Sample code: Output: 7 |
const char* string::data () const
Sample code: Output: The strings are equal |
size_type string::copy(char* szBuf, size_type nLength, size_type nIndex = 0) const
Sample code: Output: black |
This function should be avoided where possible as it is relatively dangerous (as it is up to the caller to provide null-termination and avoid buffer overflows).