如何to pad string i...
Notifications
Clear all

如何to pad string in Java

RSS

(@sathish)
Member Moderator
Joined: 1 year ago
帖子:1391
13/05/2021 11:09 am

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.


Quote
(@anamika)
Noble Member
Joined: 1 year ago
Posts: 1381
13/05/2021 11:11 am
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*charsDisplay '*' for characters of password:Stringpassword="secret123";Stringpadded=String.format("%"+password.length()+"s","").replace(' ','*');output has the same length as the password string:secret123*********

ReplyQuote
Share:
Baidu