Add leading zeros to a C++ string
This post will discuss how to add leading zeros to a string in C++.
1. Using std::string constructor
A simple solution is to create a string consisting of all zeros of the required length using the std::string constructor. Then append the original string to it. Following is a C++ implementation of the same:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <string> #include <algorithm> int main() { std::string str = "11011"; size_t n = 8; int precision = n - std::min(n, str.size()); std::string s = std::string(precision, '0').append(str); std::cout << s << std::endl; // 00011011 return 0; } |
2. Using string::insert
The above solution creates a new string. To insert the leading zeros in the original string, consider using the string::insert function. Its usage is demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <string> #include <algorithm> int main() { std::string str = "11011"; size_t n = 8; int precision = n - std::min(n, str.size()); str.insert(0, precision, '0'); std::cout << str << std::endl; // 00011011 return 0; } |
3. Using std::ostringstream
Another option is to use the std::setw manipulator with std::ostringstream to pad a string with leading zeros. This would need <sstream> and <iomanip> headers.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> #include <string> #include <algorithm> #include <sstream> #include <iomanip> int main() { std::string str = "11011"; size_t n = 8; std::ostringstream ss; ss << std::setw(n) << std::setfill('0') << str; std::string s = ss.str(); std::cout << s << std::endl; // 00011011 return 0; } |
4. Using std::format
Starting with C++20, we can use the formatting library to add leading zeros to the string. It provides the std::format function in the header <format>. With C++17 and before, we can use the {fmt} library to achieve the same.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <iostream> #include <string> #include <algorithm> #include <format> int main() { std::string str = "11011"; std::cout << std::format("{:08}", str); // 00011011 return 0; } |
That’s all about adding leading zeros to a string in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)