Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we use String.format() to pad/prefix with a character with desired length?

Can java.lang.String.format(String str, String str1) be used for adding prefix of a particular character.

I could do this for a number like:

int sendID = 202022;
String usiSuffix = String.format("%032d", sendID);

It makes a String of length 32 and leftpadded with 0s : 00000000000000000000000000202022

How to achieve the same thing when sendID is a String like:

String sendID = "AABB";

And I want an output like: 0000000000000000000000000000AABB

like image 888
Swagatika Avatar asked Mar 26 '13 10:03

Swagatika


People also ask

What is string format () used for?

In java, String format() method returns a formatted string using the given locale, specified format string, and arguments. We can concatenate the strings using this method and at the same time, we can format the output concatenated string.

How do you add padding to a string?

Use the String. format() method to pad the string with spaces on left and right, and then replace these spaces with the given character using String. replace() method. For left padding, the syntax to use the String.

How do you ensure a string is a certain length in python?

In Python, strings have a built-in method named ljust . The method lets you pad a string with characters up to a certain length. The ljust method means "left-justify"; this makes sense because your string will be to the left after adjustment up to the specified length.

How do I pad a string in Javascript?

padStart() The padStart() method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start of the current string.


1 Answers

You can use this hackish way to get your output:

String sendID = "AABB";
String output = String.format("%0"+(32-sendID.length())+"d%s", 0, sendID);

Demo: http://ideone.com/UNVjqS

like image 132
anubhava Avatar answered Oct 04 '22 02:10

anubhava