Monthly Archives: August 2021

C++ || How To Pad Left, Pad Right & Pad Center A String Of Fixed Length Using C++

The following is a module with functions which demonstrates how to pad left, pad right, and pad center a string of a fixed length using C++.

The functions demonstrated on this page left, right, and center aligns the characters in a string by padding them on the left and right with a specified character, of a specified total length.

The returned string is padded with as many padding characters needed to reach a length of the specified total width.

The padding character is user defined, but if no padding character is specified, the string is padded using a whitespace (‘ ‘).


1. Pad Left

The example below demonstrates the use of ‘Utils::padLeft‘ to right align the characters in a string by padding them on the left with a specified character, of a specified total length.

In this example, the default padding character is used to pad the string, which is a whitespace (‘ ‘).


2. Pad Right

The example below demonstrates the use of ‘Utils::padRight‘ to left align the characters in a string by padding them on the right with a specified character, of a specified total length.

In this example, the default padding character is used to pad the string, which is a whitespace (‘ ‘).


3. Pad Center

The example below demonstrates the use of ‘Utils::padCenter‘ to center align the characters in a string by padding them on the left and right with a specified character, of a specified total length.

In this example, the default padding character is used to pad the string, which is a whitespace (‘ ‘).


4. Utils Namespace

The following is the Utils Namespace. Include this in your project to start using!


5. More Examples

Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.