Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.5k points)

Is there some easy way to pad Strings in Java?

Seems like something that should be in some StringUtil-like API, but I can't find anything that does this.

1 Answer

0 votes
by (46k points)

Use, String.format() to left/right pad a given string.

public static String padRight(String s, int n) {

     return String.format("%-" + n + "s", s);  

}

public static String padLeft(String s, int n) {

    return String.format("%" + n + "s", s);  

}

...

public static void main(String args[]) throws Exception {

 System.out.println(padRight("Howto", 20) + "*");

 System.out.println(padLeft("Howto", 20) + "*");

}

And the output is:

Howto               *

               Howto*

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...