Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true

Categories


C Books Guide and List
C++ Books Guide and List
Best Java Books

3.8k questions

4k answers

117 comments

10.7k users

0 votes
18 views
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.
asked by Guru (27.1k points) 35 53 115

2 Answers

0 votes

 

Since 1.5, String.format() can be used to left/right pad a given string.
 
public static String padRight(String s, int n) {
     return String.format("%1$-" + n + "s", s);  
}
 
public static String padLeft(String s, int n) {
    return String.format("%1$" + n + "s", s);  
}
 
...
 
public static void main(String args[]) throws Exception {
 System.out.println(padRight("Howto", 20) + "*");
 System.out.println(padLeft("Howto", 20) + "*");
}
/*
  output :
     Howto               *
                    Howto*
*/
 
 
answered by Expert (13.2k points) 29 44 63
0 votes
 
Padding to 10 characters:
 
String.format("%10s", "foo").replace(' ', '*');
String.format("%-10s", "bar").replace(' ', '*');
String.format("%10s", "longer than 10 chars").replace(' ', '*');
output:
 
  *******foo
  bar*******
  longer*than*10*chars
Display '*' for characters of password:
 
String password = "secret123";
String padded = String.format("%"+password.length()+"s", "").replace(' ', '*');
output has the same length as the password string:
 
  secret123
  *********
 
answered by Guru (24.6k points) 32 59 94

Related questions

0 votes
1 answer 18 views
18 views asked by john Guru (27.1k points) 35 53 115
0 votes
1 answer 75 views
75 views asked by john Guru (27.1k points) 35 53 115
0 votes
2 answers 39 views
39 views asked by sara Guru (24.6k points) 32 59 94
+1 vote
1 answer 45 views
45 views asked by john Guru (27.1k points) 35 53 115
0 votes
1 answer 61 views
61 views asked by sara Guru (24.6k points) 32 59 94
...