Pad a String with Spaces in
Java
Since Java 1.5 we can use the
method java.lang.String.format(String
, object) and use printf like format.
The
format string "%1$15s" will
do the job. Where 1$ indicates the
argument index, s indicates that
the argument is a String 15 represent the
minimal width of the String. Putting it all together: "%1$15s".
public static String
fixedLengthString(String string, int length) {
return String.format("%1$"+length+ "s", string);
}
Example
import java.util.Scanner;
public class InputStringFormating
{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("================================");
for(int i=0;i<1 span="">i++) 1>
{
String s1 = sc.next();
sc.close();
String paddedString = (String.format("%1$-"+10+"s", s1)).replace(" ", "*");
System.out.println(paddedString);
}
System.out.println("================================");
}
Input
java
Output
================================
java******
================================
Using StringBuilder
We
can achieve this with StringBuilder and some procedural logic
class StringPaddingExample
{
public static void main(String[] args) {
String str = padLeftZeros("java", 10);
System.out.println(str);
}
public static String padLeftZeros(String inputString, int length) {
if (inputString.length() >= length) {
return inputString;
}
StringBuilder sb = new StringBuilder();
while (sb.length() < length - inputString.length()) {
sb.append('0');
}
sb.append(inputString);
return sb.toString();
}
}
Input
java
Output
000000java
That’s all for a basic String padding in
java, I hope that you enjoyed reading it and let us know in comment if anything
more info you want.
0 comments:
Post a Comment