Jump to content

C++ Language/Std/Strings/StringClass/Indexing

From Wikibooks, open books for an open world

Like any STL collection, you could iterate through string data using std::string::iterator. A std::string object uses contiguous memory for storing its characters. Application code is allowed to directly access the un-terminated character data (either via char* pcVar = &strVar[0]; or char* pcVar = strVar.data();) as long as it stays within the string's allocation area, and finishes its work before the next std::string operation. More conveniently, strVar.c_str() is like strVar.data() except that c_str() temporarily adds a '\0' at the end of the data-characters (making the buffer temporarily compatible with C-Runtime functions).

Additional information about string indexing (includes interactive examples)