Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add leading zero's to string, without (s)printf

Tags:

c++

I want to add a variable of leading zero's to a string. I couldn't find anything on Google, without someone mentioning (s)printf, but I want to do this without (s)printf.

Does anybody of the readers know a way?

like image 620
Guus Geurkink Avatar asked May 26 '11 19:05

Guus Geurkink


People also ask

How do you add leading zeros to a string?

The format() method of String class in Java 5 is the first choice. You just need to add "%03d" to add 3 leading zeros in an Integer. Formatting instruction to String starts with "%" and 0 is the character which is used in padding. By default left padding is used, 3 is the size and d is used to print integers.

How do I print the leading zeros of a string?

Use the str. zfill() Function to Display a Number With Leading Zeros in Python. The str. zfill(width) function is utilized to return the numeric string; its zeros are automatically filled at the left side of the given width , which is the sole attribute that the function takes.

How do you add leading zeros to a string in Python?

For padding a string with leading zeros, we use the zfill() method, which adds 0's at the starting point of the string to extend the size of the string to the preferred size. In short, we use the left padding method, which takes the string size as an argument and displays the string with the padded output.

How can I pad a value with leading zeros?

To pad an integer with leading zeros to a specific length To display the integer as a decimal value, call its ToString(String) method, and pass the string "Dn" as the value of the format parameter, where n represents the minimum length of the string.


2 Answers

I can give this one-line solution if you want a field of n_zero zeros:

auto new_str = std::string(n_zero - std::min(n_zero, old_str.length()), '0') + old_str; 

For example: old_str = "45"; n_zero = 4; new_str = "0045";

like image 103
Ruslan Guseinov Avatar answered Sep 24 '22 12:09

Ruslan Guseinov


You could use std::string::insert, std::stringstream with stream manipulators, or Boost.Format :

#include <string> #include <iostream> #include <iomanip> #include <boost/format.hpp> #include <sstream>  int main() {   std::string s("12");   s.insert(0, 3, '0');   std::cout << s << "\n";    std::ostringstream ss;   ss << std::setw(5) << std::setfill('0') << 12 << "\n";   std::string s2(ss.str());   std::cout << s2;    boost::format fmt("%05d\n");   fmt % 12;   std::string s3 = fmt.str();   std::cout << s3; } 
like image 45
Robᵩ Avatar answered Sep 21 '22 12:09

Robᵩ