Swagatika
Swagatika

Reputation: 3436

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

Upvotes: 13

Views: 47471

Answers (5)

Brian Agnew
Brian Agnew

Reputation: 272237

You can't use String.format() for padding with arbitrary characters. Perhaps Apache Commons StringUtils.leftPad() would be of use for a concise solution ? Note there's also a StringUtils.rightPad() too.

Upvotes: 5

Koziołek
Koziołek

Reputation: 2874

I just add some Java 8 code if someone need it in future:

public class App {
    public static void main(String[] args) {
        System.out.println(leftpad("m m", 2, '@'));
        System.out.println(leftpad("m m", 5, '@'));
    }

    static String leftpad(String s, int nb, char pad) {
        return Optional.of(nb - s.length())
                .filter(i -> i > 0)
                .map(i-> String.format("%" + i + "s", "").replace(" ", pad + "") + s)
                .orElse(s);
    }

}

This version supports adding any char as padding

Upvotes: 2

anubhava
anubhava

Reputation: 784988

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

Upvotes: 18

user3534893
user3534893

Reputation: 1

This is how I solved this issue using the base jdks String.format function

String sendId="AABB";
int length=20;
String.format("%"+length+"s",sendId).replaceAll(" ","0")

Upvotes: 0

Jayamohan
Jayamohan

Reputation: 12924

You can do as below if you really want to use String.format,

String sendID = "AABB";
String.format("%32s", sendID ).replace(' ', '0')

Other than String.format you can find many solutions here.

Edit: Thanks for Brian to point of the issue. The above wont work for input with spaces. You can try as below. But I wont suggest the below operation as it has too many string operation.

String sendID = "AA BB";
String suffix = String.format("%32s", "").replace(' ', '0') + sendID;
sendID = suffix.substring(sendID.length());

You can also try using StringUtils.leftPad

StringUtils.leftPad(sendID, 32 - sendID.length(), '0');

Upvotes: 13

Related Questions