The append() Function

◀ Append Operators▶ The substr() Function
Amazon Closely related to += operator are the append() functions which allow you to append a string, a character array, or a character to a string. They work like += operator but they are more powerful in that they allow you to, for example, append multiple identical characters of the given count.

string & append(const string & s);
string & append(const string & s, int pos, int n);
string & append(int n, char c);
string & append(const char *cs);
string & append(const char *cs, int n);

The first function simply appends s to the invoking object. The second one appends s, starting at index pos and spanning n characters in s. It will not go beyond the end of s if n is too big. The third one appends n’s c. The fourth one appends cs. The fifth one appends the first n characters in cs.

Here are several examples:

string a = “Robert ”;
string b = “is not ”;
char *c = “superb ”;
char d = ‘d’;
a.append(b); /* a is “Robert is not ” */
a = “Robert ”;
a.append(b, 0, 3); /* a is “Robert is ” */
a.append(c, 6); /* a is “Robert is superb” */
a = “Robert ”;
a.append(5, d); /* a is “Robert ddddd” */

Now let’s look at how to extract a part of a string, also known as a substring, which is a common string manipulation task!
◀ Append Operators▶ The substr() Function

fShare
Questions? Let me know!