4.1. Padding a String
Problem
You need to “pad,” or fill, a string
with a number of occurrences of some character to a certain width. For
example, you may want to pad the string "Chapter
1" to 20 characters wide with periods, so that it looks
like "Chapter 1...........“.
Solution
Use string’s insert
and append member functions to pad a
string with characters on the beginning or end. For example, to pad the end of a string to
20 characters with X’s:
std::string s = "foo"; s.append(20 - s.length(), 'X');
To pad the string at the beginning instead:
s.insert(s.begin(), 20 - s.length(), 'X');
Discussion
The difference in usage between the two functions is insert’s first parameter. It is an iterator that points to the character
immediately to the right of where the insert should occur. The begin member function returns an iterator pointing to the first element in
the string, so in the example, the series of characters is inserted to the left of that.
The parameters common to both functions are the number of times to repeat the character
and the character itself.
insert and append are actually member functions of the basic_string class template in the <string> header (string is a
typedef for basic_string<char> and wstring is a
typedef for basic_string<wchar_t>), so they work for strings of narrow or wide
characters. Using them as needed, as in the above example, will work fine, but if you are
using basic_string member functions from within your own generic utility functions, you should build ...