Constructors◀ C++ String Class▶ Test for String Equality Amazon
is such a useful class, it helps to learn the functions it provides. First, let’s learn its constructors. There are six constructors string provides.
The following table shows the constructor prototypes and the corresponding descriptions. The string class uses string::npos
as a symbolic constant for the maximum possible length of a string.
|string()||creates an empty string object|
|string(const string s, int n, int n2)||creates a string and initializes it to contents starting at index n spanning n2 characters in s|
|string(const char *cs)||creates a string and initializes it to cs|
|string(int n, char c)||creates a string and initializes it to ns c|
|string(const char *cs, int n)||creates a string and initializes it to the first n elements in cs; if n is too big the string will contain garbage data|
|string(pt b, pt e)||initializes string object to the values of range [b, e); b and e can be pointers pointing to some element in a char array|
Let’s pay attention to the second constructor as it is useful. Here is its real prototype:
string(const string & s, int pos = 0; int n = string::npos);
The second argument, pos
, specifies the starting copying position. The third argument, n
, specifies how many characters should be copied to the invoking object.
If you just give the first argument, the entire s
is copied to the invoking object. If the third argument exceeds the length of the available characters, the constructor simply copies the remaining string starting at pos
; it doesn’t give you garbage data. Here are several examples:
string Cindy("Cindy has inner beauty");
string ex(Cindy); /* ex is “Cindy has inner beauty” */
string ex2(Cindy, 6); /* ex2 is “has inner beauty” */
string ex3(Cindy, 6, 3); /* ex3 is “has” */
string ex4(Cindy, 6, 1000); /* ex4 is “has inner beauty” */
Now that you are familiar with string constructors let’s move on to string’s other properties!
◀ C++ String Class▶ Test for String Equality