String (C++)
From Wikipedia, the free encyclopedia
In the C++ programming language, the std::string
class is a standard representation for a string of text. This class removes many of the problems introduced by C-style strings by putting the onus of memory ownership on the string
class rather than on the programmer. This class also provides implicit construction from C-style strings, explicit conversion to C-style strings, and a comparison operator so that strings can be compared using ==
, !=
, <
, >
, <=
, >=
, just like integers rather than the cumbersome and error-prone strcmp
calls required with C-style strings.
[edit] Usage
The std::string
class is found in the string
header and in the std
namespace. So simple usage includes:
#include <iostream> #include <cassert> // For assert(). #include <string> int main() { std::string foo = "hi"; using std::string; // Now we can just say "string". string bar = "hi"; assert(foo == bar); // Strings can be compared with operator ==. std::cout << foo + bar << "\n"; // Prints "hihi". return 0; }
Because a string may be stored by value, copying may take as long as θ(n) (i.e., copying takes time proportional to the length of the string). For that reason, string
s are generally passed by const reference, as in
void print_the_string(const std::string& str) { std::cout << str; }
Also, because a char*
can be implicitly converted to a const std::string&
(albeit in θ(n) time), this is a convenient type for a function to take. For example:
const char* foo = "Hello"; std::string bar = "world"; print_the_string(foo); // Converts foo to a const std::string. print_the_string(" "); // Converts " " to a const std::string. print_the_string(bar); // Passes bar by const reference.