Skip to Main Content
C++ Cookbook
book

C++ Cookbook

by D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell
November 2005
Beginner to intermediate content levelBeginner to intermediate
594 pages
16h 23m
English
O'Reilly Media, Inc.
Content preview from C++ Cookbook

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ System Programming Cookbook

C++ System Programming Cookbook

Onorato Vaticone

Publisher Resources

ISBN: 0596007612Supplemental ContentErrata Page