C-style strings, called C-strings, consist of characters stored in an array. We will look at them after arrays and pointers.
C++ standard library strings are usuable in a manner
similar to the built-in types.
Remember, a variable's/object's type determines what operations
may be performed on it.
Below are some ways C++ strings
(variables/objects of type string
)
can be used.
#include <string>
is required
define |
string str1;
|
|
---|---|---|
string str2 = "literal";
|
|
|
string str3("literal");
|
|
|
string str4(n, 'c');
|
|
|
output |
cout << str2
|
|
input |
cin >> str2
|
|
assign |
str2 = str1
|
|
concatenate |
str1 + str2
|
|
append |
str1 += str2
|
|
compare |
str1 == str2
Also: != ,
< ,
<= ,
> , and
>=
|
|
length |
str1.length()
|
|
index |
str1[index]
|
|
C-string |
str1.c_str()
|
|
search |
str1.find(string str2)
str1.find(string str2, size_type index)
|
|
|
||
substring |
str1.substr(size_type index, size_type length)
|
|
|
|
A special integer type is provided that is guaranteed
to be large enough to represent
string
's of any length (for the platform).
The type is string::size_type
.
Unless you are doing something unusual (very large strings)
you can use an int
in its place.
Is a C++
string
implemented as a character array?
The user of the class doesn't need know the internals of the class,
just how to use it.
It is up to the implementer of the class to implement it well.