- String (C++)
In the
C++ programming language, thestd::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 thestring
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
calls required with C-style strings.strcmp Usage
The
std::string
class is found in thestring
header and in thestd
namespace. So simple usage includes: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). (Although GNU and Dinkumware C++ libraries use
reference counting andcopy-on-write technique to avoid unnecessary copying.) For that reason,string
s are generally passed by const reference, as inAlso, because a
char*
can be implicitly converted to aconst std::string&
(albeit in "θ"("n") time), this is a convenient type for a function to take. For example:Operators
The string class is fitted with a number of mathematical and logical operators for ease of use. All operators for the string class have member function equivalents, and all can accept another string or character-string, so operators are purely for appearance and have no other advantage. All, except the assignment operator, can also accept single characters. Most allow the left operand to be a character-string.
The most basic, and obvious, is the assignment operator.
The string class also has a good few options for
concatenation .Strings can also be tested for equality and inequality.Also,
!=, <=,
and>=
are valid operations for strings. One advantage of strings over c-strings is that when two c-strings are compared, it is implementation defined as to whether the contents or addresses are compared. Strings, however, always compare by contents and never by address.Lastly is the random access operator. It allows a string to act as a character-string, returning a reference to a character.
Wikimedia Foundation. 2010.