String s1= "SAM";
int x=30;
System.out.printf(s1); // prints at left most
s1=String.format("d",x);// formatting a number by 3 digits
System.out.printf("s",s1);//padding by 15 digits
System.out.println();
the task is to print the string and number in correct padding i.e whatever the length of string the number should start at 16th position. thanks in advance.
CodePudding user response:
you can use the following template to achieve the result
String Wrd = "SPKJ";
int intVAlFor = 35;
String Vn = "";
if(Wrd.length()<= 15){
Vn = String.format("%0" (15 - Wrd.length() ) "d%s",0 ,Wrd);
Vn = Vn Integer.toString(intVAlFor);
} else {
Vn = Wrd.substring(0, 15);
Vn = Vn Integer.toString(intVAlFor);
}
System.out.println(Vn);
Output :
00000000000SPKJ35
You can change the formatting respective to formatting you want to use (Right Padding / Left Padding by making changes in String.format()
)
CodePudding user response:
Refer to javadoc for format string syntax.
In order for the string to be left justified, you need to use %-15s
. And if s1
is longer than 15 charatcters, you need to shorten it.
String s1 = "antidisestablishmentarianism";
int len = s1.length();
if (len > 15) {
s1 = s1.substring(0, 15);
}
System.out.printf("%-15sd%n", s1, len);
Running the above code prints the following.
antidisestablis028
And using the example in your question.
String s1 = "SAM";
int len = s1.length();
if (len > 15) {
s1 = s1.substring(0, 15);
}
int x = 30;
System.out.printf("%-15sd%n", s1, x);
Output is
SAM 030
CodePudding user response:
Your example is already padded by 13 spaces, so the number is at 16th position. So I thought you might want to padded by 15 in between of them. So the easiest is to use an empty string like following:
String s = "SAM";
int x = 30;
System.out.printf(s); //Prints at the most left
s = String.format("d", x); //Format the number by 3 digits
System.out.printf("s%s", "", s); //Padded by 15 digits
System.out.println();
SAM 030