Learn C++

July 18th, 2010

17.7 — std::string inserting

Inserting

Inserting characters into an existing string can be done via the insert() function.

string& string::insert (size_type index, const string& str)
string& string::insert (size_type index, const char* str)

  • Both functions insert the characters of str into the string at index
  • Both function return *this so they can be “chained”.
  • Both functions throw out_of_range if index is invalid
  • Both functions throw a length_error exception if the result exceeds the maximum number of characters.
  • In the C-style string version, str must not be NULL.

Sample code:

string sString("aaaa");
cout << sString << endl;

sString.insert(2, string("bbbb"));
cout << sString << endl;

sString.insert(4, "cccc");
cout << sString << endl;

Output:

aaaa
aabbbbaa
aabbccccbbaa

Here’s a crazy version of insert() that allows you to insert a substring into a string at an arbitrary index:

string& string::insert (size_type index, const string& str, size_type startindex, size_type num)

  • This function inserts num characters str, starting from startindex, into the string at index.
  • Returns *this so it can be “chained”.
  • Throws an out_of_range if index or startindex is out of bounds
  • Throws a length_error exception if the result exceeds the maximum number of characters.

Sample code:

string sString("aaaa");

const string sInsert("01234567");
sString.insert(2, sInsert, 3, 4); // insert substring of sInsert from index [3,7) into sString at index 2
cout << sString << endl;

Output:

aa3456aa

There is a flavor of insert() that inserts the first portion of a C-style string:

string& string::insert(size_type index, const char* str, size_type len)

  • Inserts len characters of str into the string at index
  • Returns *this so it can be “chained”.
  • Throws an out_of_range exception if the index is invalid
  • Throws a length_error exception if the result exceeds the maximum number of characters.
  • Ignores special characters (such as ‘\0′)

Sample code:

string sString("aaaa");

sString.insert(2, "bcdef", 3);
cout << sString << endl;

Output:

aabcdaa

There’s also a flavor of insert() that inserts the same character multiple times:

string& string::insert(size_type index, size_type num, char c)

  • Inserts num instances of char c into the string at index
  • Returns *this so it can be “chained”.
  • Throws an out_of_range exception if the index is invalid
  • Throws a length_error exception if the result exceeds the maximum number of characters.

Sample code:

string sString("aaaa");

sString.insert(2, 4, 'c');
cout << sString << endl;

Output:

aaccccaa

And finally, the insert() function also has three different versions that use iterators:

void insert(iterator it, size_type num, char c)
iterator string::insert(iterator it, char c)
void string::insert(iterator it, InputIterator begin, InputIterator end)

  • The first function inserts num instances of the character c before the iterator it.
  • The second inserts a single character c before the iterator it, and returns an iterator to the position of the character inserted.
  • The third inserts all characters between [begin,end) before the iterator it.
  • All functions throw a length_error exception if the result exceeds the maximum number of characters.

Index
17.6 — std::string appending
July 18th, 2010

17.6 — std::string appending

Appending

Appending strings to the end of an existing string is easy using either operator+=, append(), or push_back() function.

string& string::operator+= (const string& str)
string& string::append (const string& str)

  • Both functions append the characters of str to the string.
  • Both function return *this so they can be “chained”.
  • Both functions throw a length_error exception if the result exceeds the maximum number of characters.

Sample code:

string sString("one");

sString += string(" two");

string sThree(" three");
sString.append(sThree);

cout << sString << endl;

Output:

one two three

There’s also a flavor of append() that can append a substring:

string& string::append (const string& str, size_type index, size_type num)

  • This function appends num characters from str, starting at index, to the string.
  • Returns *this so it can be “chained”.
  • Throws an out_of_range if index is out of bounds
  • Throws a length_error exception if the result exceeds the maximum number of characters.

Sample code:

string sString("one ");

const string sTemp("twothreefour");
sString.append(sTemp, 3, 5); // append substring of sTemp starting at index 3 of length 5
cout << sString << endl;

Output:

one three

Operator+= and append() also have versions that work on C-style strings:

string& string::operator+= (const char* str)
string& string::append (const char* str)

  • Both functions append the characters of str to the string.
  • Both function return *this so they can be “chained”.
  • Both functions throw a length_error exception if the result exceeds the maximum number of characters.
  • str should not be NULL.

Sample code:

string sString("one");

sString += " two";
sString.append(" three");
cout << sString << endl;

Output:

one two three

There is an additional flavor of append() that works on C-style strings:

string& string::append (const char* str, size_type len)

  • Appends the first len characters of str to the string.
  • Returns *this so they can be “chained”.
  • Throw a length_error exception if the result exceeds the maximum number of characters.
  • Ignores special characters (including ‘\0′)

Sample code:

string sString("one");

sString.append("threefour", 5);
cout << sString << endl;

Output:

one three

This function is dangerous and its use is not recommended.

There is also a set of functions that append characters. Note that the name of the non-operator function to append a character is push_back(), not append()!

string& string::operator+= (char c)
void string::push_back (char c)

  • Both functions append the the character c to the string.
  • Operator += returns *this so it can be “chained”.
  • Both functions throw a length_error exception if the result exceeds the maximum number of characters.

Sample code:

string sString("one");

sString += ' ';
sString.append('2');
cout << sString << endl;

Output:

one 2

Now you might be wondering why the name of the function is push_back() and not append(). This follows a naming convention used for stacks, where push_back() is the function that adds a single item to the end of the stack. If you envision a string as a stack of characters, using push_back() to add a single character to the end makes sense. However, the lack of an append() function is inconsistent in my view!

It turns out there is an append() function for characters, that looks like this:

string& string::append (size_type num, char c)

  • Adds num occurrences of the character c to the string
  • Returns *this so it can be “chained”.
  • Throws a length_error exception if the result exceeds the maximum number of characters.

Sample code:

string sString("aaa");

sString.append(4, 'b');
cout << sString << endl;

Output:

aaabbbb

There’s one final flavor of append() that you won’t understand unless you know what iterators are. If you’re not familiar with iterators, you can ignore this function.

string& string::append (InputIterator start, InputIterator end)

  • Appends all characters from the range [start, end) (including start up to but not including end)
  • Returns *this so it can be “chained”.
  • Throws a length_error exception if the result exceeds the maximum number of characters.

17.7 — std::string inserting
Index
17.5 — std::string assignment and swapping
July 18th, 2010

17.5 — std::string assignment and swapping

String assignment

The easiest way to assign a value to a string is to the use the overloaded operator= function. There is also an assign() member function that duplicates some of this functionality.

string& string::operator= (const string& str)
string& string::assign (const string& str)
string& string::operator= (const char* str)
string& string::assign (const char* str)
string& string::operator= (char c)

  • These functions assign values of various types to the string.
  • These functions return *this so they can be “chained”.
  • Note that there is no assign() function that takes a single char.

Sample code:

string sString;

// Assign a string value
sString = string("One");
cout << sString << endl;

const string sTwo("Two");
sString.assign(sTwo);
cout << sString << endl;

// Assign a C-style string
sString = "Three";
cout << sString << endl;

sString.assign("Four");
cout << sString << endl;

// Assign a char
sString = '5';
cout << sString << endl;

// Chain assignment
string sOther;
sString = sOther = "Six";
cout << sString << " " << sOther << endl;

Output:

One
Two
Three
Four
5
Six Six

The assign() member function also comes in a few other flavors:

string& string::assign (const string& str, size_type index, size_type len)

  • Assigns a substring of str, starting from index, and of length len
  • Throws an out_of_range exception if the index is out of bounds
  • Returns *this so it can be “chained”.

Sample code:

const string sSource("abcdefg");
string sDest;

sDest.assign(sSource, 2, 4); // assign a substring of source from index 2 of length 4
cout << sDest << endl;

Output:

cdef

string& string::assign (const char* chars, size_type len)

  • Assigns len characters from the C-style array chars
  • Ignores special characters (including ‘\0′)
  • Throws an length_error exception if the result exceeds the maximum number of characters
  • Returns *this so it can be “chained”.

Sample code:

string sDest;

sDest.assign("abcdefg", 4);
cout << sDest << endl;

Output:

abcd

This function is potentially dangerous and it’s use is not recommended.

string& string::assign (size_type len, char c)

  • Assigns len occurrences of the character c
  • Throws an length_error exception if the result exceeds the maximum number of characters
  • Returns *this so it can be “chained”.

Sample code:

string sDest;

sDest.assign(4, 'g');
cout << sDest << endl;

Output:

gggg

Swapping

If you have two strings and want to swap their values, there are two functions both named swap() that you can use.

void string::swap (string &str)
void swap (string &str1, string &str2)

  • Both functions swap the value of the two strings. The member function swaps *this and str, the global function swaps str1 and str2.
  • These functions are efficient and should be used instead of assignments to perform a string swap.

Sample code:

string sStr1("red");
string sStr2("blue);

cout << sStr1 << " " << sStr2 << endl;
swap(sStr1, sStr2);
cout << sStr1 << " " << sStr2 << endl;
sStr1.swap(sStr2);
cout << sStr1 << " " << sStr2 << endl;

Output:

red blue
blue red
red blue

17.6 — std::string appending
Index
17.4 — std::string character access and conversion to c-style strings
March 6th, 2009
December 11th, 2008

Please report any site issues here

Hey everyone,

I’ve just upgraded the web site to wordpress 2.7. If you’ve noticed that anything has broken, please report it here.

No additional downtime is expected at this time. :)

Thanks,
Alex