This question already has answers here:
How can I pad a String in Java?
(32 answers)
Closed 5 years ago.
I've seen similar questions here and here.
But am not getting how to left pad a String with Zero.
input: "129018"
output: "0000129018"
The total output length should be TEN.
If your string contains numbers only, you can make it an integer and then do padding:
String.format("%010d", Integer.parseInt(mystring));
If not I would like to know how it can be done.
String paddedString = org.apache.commons.lang.StringUtils.leftPad("129018", 10, "0")
the second parameter is the desired output length
"0" is the padding char
This will pad left any string to a total width of 10 without worrying about parse errors:
String unpadded = "12345";
String padded = "##########".substring(unpadded.length()) + unpadded;
//unpadded is "12345"
//padded is "#####12345"
If you want to pad right:
String unpadded = "12345";
String padded = unpadded + "##########".substring(unpadded.length());
//unpadded is "12345"
//padded is "12345#####"
You can replace the "#" characters with whatever character you would like to pad with, repeated the amount of times that you want the total width of the string to be. E.g. if you want to add zeros to the left so that the whole string is 15 characters long:
String unpadded = "12345";
String padded = "000000000000000".substring(unpadded.length()) + unpadded;
//unpadded is "12345"
//padded is "000000000012345"
The benefit of this over khachik's answer is that this does not use Integer.parseInt, which can throw an Exception (for example, if the number you want to pad is too large like 12147483647). The disadvantage is that if what you're padding is already an int, then you'll have to convert it to a String and back, which is undesirable.
So, if you know for sure that it's an int, khachik's answer works great. If not, then this is a possible strategy.
String str = "129018";
String str2 = String.format("%10s", str).replace(' ', '0');
System.out.println(str2);
String str = "129018";
StringBuilder sb = new StringBuilder();
for (int toPrepend=10-str.length(); toPrepend>0; toPrepend--) {
sb.append('0');
}
sb.append(str);
String result = sb.toString();
You may use apache commons StringUtils
StringUtils.leftPad("129018", 10, "0");
https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#leftPad(java.lang.String,%20int,%20char)
To format String use
import org.apache.commons.lang.StringUtils;
public class test {
public static void main(String[] args) {
String result = StringUtils.leftPad("wrwer", 10, "0");
System.out.println("The String : " + result);
}
}
Output : The String : 00000wrwer
Where the first argument is the string to be formatted, Second argument is the length of the desired output length and third argument is the char with which the string is to be padded.
Use the link to download the jar http://commons.apache.org/proper/commons-lang/download_lang.cgi
If you need performance and know the maximum size of the string use this:
String zeroPad = "0000000000000000";
String str0 = zeroPad.substring(str.length()) + str;
Be aware of the maximum string size. If it is bigger then the StringBuffer size, you'll get a java.lang.StringIndexOutOfBoundsException.
An old question, but I also have two methods.
For a fixed (predefined) length:
public static String fill(String text) {
if (text.length() >= 10)
return text;
else
return "0000000000".substring(text.length()) + text;
}
For a variable length:
public static String fill(String text, int size) {
StringBuilder builder = new StringBuilder(text);
while (builder.length() < size) {
builder.append('0');
}
return builder.toString();
}
I prefer this code:
public final class StrMgr {
public static String rightPad(String input, int length, String fill){
String pad = input.trim() + String.format("%"+length+"s", "").replace(" ", fill);
return pad.substring(0, length);
}
public static String leftPad(String input, int length, String fill){
String pad = String.format("%"+length+"s", "").replace(" ", fill) + input.trim();
return pad.substring(pad.length() - length, pad.length());
}
}
and then:
System.out.println(StrMgr.leftPad("hello", 20, "x"));
System.out.println(StrMgr.rightPad("hello", 20, "x"));
Use Google Guava:
Maven:
<dependency>
<artifactId>guava</artifactId>
<groupId>com.google.guava</groupId>
<version>14.0.1</version>
</dependency>
Sample code:
Strings.padStart("129018", 10, '0') returns "0000129018"
Based on #Haroldo MacĂȘdo's answer, I created a method in my custom Utils class such as
/**
* Left padding a string with the given character
*
* #param str The string to be padded
* #param length The total fix length of the string
* #param padChar The pad character
* #return The padded string
*/
public static String padLeft(String str, int length, String padChar) {
String pad = "";
for (int i = 0; i < length; i++) {
pad += padChar;
}
return pad.substring(str.length()) + str;
}
Then call Utils.padLeft(str, 10, "0");
Here's another approach:
int pad = 4;
char[] temp = (new String(new char[pad]) + "129018").toCharArray()
Arrays.fill(temp, 0, pad, '0');
System.out.println(temp)
Here's my solution:
String s = Integer.toBinaryString(5); //Convert decimal to binary
int p = 8; //preferred length
for(int g=0,j=s.length();g<p-j;g++, s= "0" + s);
System.out.println(s);
Output: 00000101
Right padding with fix length-10:
String.format("%1$-10s", "abc")
Left padding with fix length-10:
String.format("%1$10s", "abc")
Here is a solution based on String.format that will work for strings and is suitable for variable length.
public static String PadLeft(String stringToPad, int padToLength){
String retValue = null;
if(stringToPad.length() < padToLength) {
retValue = String.format("%0" + String.valueOf(padToLength - stringToPad.length()) + "d%s",0,stringToPad);
}
else{
retValue = stringToPad;
}
return retValue;
}
public static void main(String[] args) {
System.out.println("'" + PadLeft("test", 10) + "'");
System.out.println("'" + PadLeft("test", 3) + "'");
System.out.println("'" + PadLeft("test", 4) + "'");
System.out.println("'" + PadLeft("test", 5) + "'");
}
Output:
'000000test'
'test'
'test'
'0test'
The solution by Satish is very good among the expected answers. I wanted to make it more general by adding variable n to format string instead of 10 chars.
int maxDigits = 10;
String str = "129018";
String formatString = "%"+n+"s";
String str2 = String.format(formatString, str).replace(' ', '0');
System.out.println(str2);
This will work in most situations
int number = -1;
int holdingDigits = 7;
System.out.println(String.format("%0"+ holdingDigits +"d", number));
Just asked this in an interview........
My answer below but this (mentioned above) is much nicer->
String.format("%05d", num);
My answer is:
static String leadingZeros(int num, int digitSize) {
//test for capacity being too small.
if (digitSize < String.valueOf(num).length()) {
return "Error : you number " + num + " is higher than the decimal system specified capacity of " + digitSize + " zeros.";
//test for capacity will exactly hold the number.
} else if (digitSize == String.valueOf(num).length()) {
return String.valueOf(num);
//else do something here to calculate if the digitSize will over flow the StringBuilder buffer java.lang.OutOfMemoryError
//else calculate and return string
} else {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < digitSize; i++) {
sb.append("0");
}
sb.append(String.valueOf(num));
return sb.substring(sb.length() - digitSize, sb.length());
}
}
Check my code that will work for integer and String.
Assume our first number is 129018. And we want to add zeros to that so the the length of final string will be 10. For that you can use following code
int number=129018;
int requiredLengthAfterPadding=10;
String resultString=Integer.toString(number);
int inputStringLengh=resultString.length();
int diff=requiredLengthAfterPadding-inputStringLengh;
if(inputStringLengh<requiredLengthAfterPadding)
{
resultString=new String(new char[diff]).replace("\0", "0")+number;
}
System.out.println(resultString);
I have used this:
DecimalFormat numFormat = new DecimalFormat("00000");
System.out.println("Code format: "+numFormat.format(123));
Result: 00123
I hope you find it useful!
Related
I have this number: 4200000000000000
I would like to leave only the first 4 digits and last 3 digits:
42000......000
Everything else should be replaced by dots. How I can implement this with some smart algorithm?
Why not use a StringBuilder and the substring method:
public static String foo(long num) {
String numToString = String.valueOf(num);
return new StringBuilder()
.append(numToString.substring(0 , 4))
.append("....")
.append(numToString.substring(numToString.length()-3, numToString.length()))
.toString();
}
When inputted 4200000000000000 it outputs:
4200....000
Or if the input is already a String:
public static String foo(String str) {
return new StringBuilder()
.append(str.substring(0 , 4))
.append("....")
.append(str.substring(str.length()-3, str.length()))
.toString();
}
Parse your number into a string and try this:
int last = 3;
int first = 4;
String number = '4200000000000000';
String start = number.substring(0,first-1);
String end = number.substring(number.length()-last,number.length()-1);
String dots = '';
for(int i = 0; i<number.length()-last-first;i++){
dots = dots + '.';
}
String result = start + dots + end;
You can use something like this,
public class Main {
public static void main(String[] args) {
System.out.println(convert("4200000000000000", 4, 3));
}
static String convert(String number, int firstDigits, int lastDigits) {
String first = number.substring(0, firstDigits);
String middle = number.substring(firstDigits, number.length() - lastDigits).replaceAll("0", ".");
String last = number.substring(number.length() - lastDigits, number.length());
return first + middle + last;
}
}
You could convert it to a char array, alter it, then convert it back into a string
char[] charArray = originalNumber.toCharArray();
for (int i; i < charArray.length; i++) {
if (i <= 4 || i >= charArray.length - 3) {
charArray[i] = ".";
}
}
String outputString = new String(charArray);
This will replace all chars from the 4th char up to the 4th from the end with '.':
String start = "4200000000000000";
System.out.println(start);
String target = start;
if (start.length() > 7) {
target = new StringBuilder()
.append(start.substring(0, 4))
.append(new String(new char[start.length() - 7]).replaceAll(".", "."))
.append(start.substring(start.length() - 3))
.toString();
}
System.out.println(target);
will print
4200000000000000
4200.........000
Using substring method of the String class :
String str = "4200000000000000";
String res = str.substring(0,4)+ str.substring(4,str.length()-3).replaceAll(".", ".") + str.substring(str.length()-3);
If you are using Apache commons library, you can use repeat method to create masking string of specified length and the overlay method of StringUtils class to overlay part of the String :
String str = "4200000000000000";
String mask= StringUtils.repeat('.', str.length()-7);
String res = StringUtils.overlay(str, mask, 4, str.length()-3);
I have a string format like this which is output of
readAllBytes(new String(Files.readAllBytes(Paths.get(data))
from a file
a+2 b+3 c+33 d+88 ......
My scenario is I want to get the data after c+" ". The position of c is not constant but c occurs only once. It may occur anywhere. My required value will always be after c+ only. The required size of value 33.....is also not constant. Can someone help me with the optimal code please? I think collections need to be used here.
You can use this regex which will let you capture the data you want,
c\+(\d+)
Explanation:
c+ matches a literal c character immediately followed by a + char
(\d+) captures the next digit(s) which you are interested in capturing.
Demo, https://regex101.com/r/jfYUPG/1
Here is a java code for demonstrating same,
public static void main(String args[]) {
String s = "a+2 b+3 c+33 d+88 ";
Pattern p = Pattern.compile("c\\+(\\d+)");
Matcher m = p.matcher(s);
if (m.find()) {
System.out.println("Data: " + m.group(1));
} else {
System.out.println("Input data doesn't match the regex");
}
}
This gives following output,
Data: 33
This code is extracting the value right after c+ up to the next space, or to the end of the string if there is no space:
String str = "a+2 b+3 c+33 d+88 ";
String find = "c+";
int index = str.indexOf(" ", str.indexOf(find) + 2);
if (index == -1)
index = str.length();
String result = str.substring(str.indexOf(find) + 2, index);
System.out.println(result);
prints
33
or in a method:
public static String getValue(String str, String find) {
int index = str.indexOf(find) + 2;
int indexSpace = str.indexOf(" ", index);
if (indexSpace == -1)
indexSpace = str.length();
return str.substring(index, indexSpace);
}
public static void main(String[] args) {
String str = "a+2 b+3 c+33 d+88 ";
String find = "c+";
System.out.println(getValue(str, find));
}
Let's say I have a couple variable and I want to format them so they're all aligned, but the variables are different lengths. For example:
String a = "abcdef";
String b = "abcdefhijk";
And I also have a price.
double price = 4.56;
How would I be able to format it so no matter how long the String is, they are aligned either way?
System.out.format("%5s %10.2f", a, price);
System.out.format("%5s %10.2f", b, price);
For example, the code above would output something like this:
abcdef 4.56
abcdefhijk 4.56
But I want it to output something like this:
abcdef 4.56
abcdefhijk 4.56
How would I go about doing so? Thanks in advance.
Use fixed size format:
Using format strings with fixed size permits to print the strings in a
table-like appearance with fixed size columns:
String rowsStrings[] = new String[] {"1",
"1234",
"1234567",
"123456789"};
String column1Format = "%-3.3s"; // fixed size 3 characters, left aligned
String column2Format = "%-8.8s"; // fixed size 8 characters, left aligned
String column3Format = "%6.6s"; // fixed size 6 characters, right aligned
String formatInfo = column1Format + " " + column2Format + " " + column3Format;
for(int i = 0; i < rowsStrings.length; i++) {
System.out.format(formatInfo, rowsStrings[i], rowsStrings[i], rowsStrings[i]);
System.out.println();
}
Output:
1 1 1
123 1234 1234
123 1234567 123456
123 12345678 123456
In your case you could find the maximum length of the strings you want to display and use that to create the appropriate format information, for example:
// find the max length
int maxLength = Math.max(a.length(), b.length());
// add some space to separate the columns
int column1Length = maxLength + 2;
// compose the fixed size format for the first column
String column1Format = "%-" + column1Length + "." + column1Length + "s";
// second column format
String column2Format = "%10.2f";
// compose the complete format information
String formatInfo = column1Format + " " + column2Format;
System.out.format(formatInfo, a, price);
System.out.println();
System.out.format(formatInfo, b, price);
Put negative sign in front of your format specifier so instead of printing 5 spaces to the left of your float value, it adjusts the space on the right until you find the ideal position. It should be fine
You can achieve it as below-
String a = "abcdef";
String b = "abcdefhijk";
double price = 4.56;
System.out.println(String.format("%-10s %-10.2f", a, price));
System.out.println(String.format("%-10s %-10.2f", b, price));
output:
abcdef 4.56
abcdefhijk 4.56
You can find the longest String, and then use Apache commons-lang StringUtils to leftPad both of your String(s). Something like,
int len = Math.max(a.length(), b.length()) + 2;
a = StringUtils.leftPad(a, len);
b = StringUtils.leftPad(b, len);
Or, if you can't use StringUtils - you could implement leftPad. First a method to generate String of whitespace. Something like,
private static String genString(int len) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < len; i++) {
sb.append(' ');
}
return sb.toString();
}
Then use it to implement leftPad - like,
private static String leftPad(String in, int len) {
return new StringBuilder(in) //
.append(genString(len - in.length() - 1)).toString();
}
And, I tested it like,
int len = Math.max(a.length(), b.length()) + 2;
System.out.format("%s %.2f%n", leftPad(a, len), price);
System.out.format("%s %.2f%n", leftPad(b, len), price);
Which outputs (as I think you wanted)
abcdef 4.56
abcdefhijk 4.56
private String addEnoughSpacesInBetween(String firstStr, String secondStr){
if (!firstStr.isEmpty() && !secondStr.isEmpty()){
String space = " ";
int totalAllowed = 55;
int multiplyFor = totalAllowed - (firstStr.length() + secondStr.length());
return StringUtils.repeat(space,multiplyFor);
}
return null;
}
I want my String to be formatted both from the left and right side, so it always keeps standing in the center.
Let's say I want the total length to be 30 symbols (let's mark spaces as stars to see clearly). I want the following result.
sampleString -> *********sampleString*********
sampleLongLongString -> *****sampleLongLongString*****
I tried to do the following.
result = padLeft("", 15) + padRight(myString, 15);
or
result = padLeft(padRight(myString, 15), 15);
For functions,
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);
}
but no result.
You can create a method to add padding based on the length of the String.
Basically, you have to decide the total/max(left+right) padding for all the Strings. Please take a look at following method.
It also manages the space inside the String. Method will just return actual String if padding can not be added according to maxPadding.
public static String getPaddedString(String str, char paddingChar) {
if (str == null) {
throw new NullPointerException("Can not add padding in null String!");
}
int maxPadding = 20;//This is what you have to decide
int length = str.length();
int padding = (maxPadding - length) / 2;//decide left and right padding
if (padding <= 0) {
return str;// return actual String if padding is less than or equal to 0
}
String empty = "", hash = "#";//hash is used as a place holder
// extra character in case of String with even length
int extra = (length % 2 == 0) ? 1 : 0;
String leftPadding = "%" + padding + "s";
String rightPadding = "%" + (padding - extra) + "s";
String strFormat = leftPadding + "%s" + rightPadding;
String formattedString = String.format(strFormat, empty, hash, empty);
//Replace space with * and hash with provided String
String paddedString = formattedString.replace(' ', paddingChar).replace(hash, str);
return paddedString;
}
Following program proves that above method works,
public class Test {
public static void main(String args[]) {
System.out.println(getPaddedString("Hello", '*'));
System.out.println(getPaddedString("Hi23", '#'));
System.out.println(getPaddedString("Test. .Test", '%'));
System.out.println(getPaddedString(
"By the way, It's to long to fix !!", '*'));
}
}
OUTPUT
************Hello************
#############Hi23############
%%%%%%%%%Test. .Test%%%%%%%%%
By the way, It's to long to fix !!
Here's an easy-to-understand method to do it:
public static String center(String string, int length, char pad) {
StringBuilder sb = new StringBuilder(length);
sb.setLength((length - string.length()) / 2);
sb.append(string);
sb.setLength(length);
return sb.toString().replace('\0', pad);
}
With this code, when the total padding required is odd, the right-side padding has one extra pad char. To change the behaviour so that the left side gets the extra pad, change line 2 to:
sb.setLength((length - string.length() + 1) / 2);
This method will do the trick.
/**
* #param int w : length of the formatted string (e.g. 30)
* #param String s : the string to be formatted
* #param char c : character to pad with
* #param boolean pr: If s is odd, pad one extra left or right
* #return the original string, with pad 'p' on both sides
*/
private String pad(String s, int w, char c, boolean pr){
int pad = w-s.length();
String p = "";
for (int i=0; i<pad/2; i++)
p = p + c;
/* If s.length is odd */
if (pad%2 == 1)
/* Pad one extra either right or left */
if (pr) s = s + c;
else s = c + s;
return (p+s+p)
}
I need to produce fixed length string to generate a character position based file. The missing characters must be filled with space character.
As an example, the field CITY has a fixed length of 15 characters. For the inputs "Chicago" and "Rio de Janeiro" the outputs are
" Chicago"
" Rio de Janeiro".
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" do the job. Where 1$ indicates the argument index, s indicates that the argument is a String and 15 represents the minimal width of the String.
Putting it all together: "%1$15s".
For a general method we have:
public static String fixedLengthString(String string, int length) {
return String.format("%1$"+length+ "s", string);
}
Maybe someone can suggest another format string to fill the empty spaces with an specific character?
Utilize String.format's padding with spaces and replace them with the desired char.
String toPad = "Apple";
String padded = String.format("%8s", toPad).replace(' ', '0');
System.out.println(padded);
Prints 000Apple.
Update more performant version (since it does not rely on String.format), that has no problem with spaces (thx to Rafael Borja for the hint).
int width = 10;
char fill = '0';
String toPad = "New York";
String padded = new String(new char[width - toPad.length()]).replace('\0', fill) + toPad;
System.out.println(padded);
Prints 00New York.
But a check needs to be added to prevent the attempt of creating a char array with negative length.
This code will have exactly the given amount of characters; filled with spaces or truncated on the right side:
private String leftpad(String text, int length) {
return String.format("%" + length + "." + length + "s", text);
}
private String rightpad(String text, int length) {
return String.format("%-" + length + "." + length + "s", text);
}
For right pad you need String.format("%0$-15s", str)
i.e. - sign will "right" pad and no - sign will "left" pad
See my example:
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("================================");
for(int i=0;i<3;i++)
{
String s1=sc.nextLine();
Scanner line = new Scanner( s1);
line=line.useDelimiter(" ");
String language = line.next();
int mark = line.nextInt();;
System.out.printf("%s%03d\n",String.format("%0$-15s", language),mark);
}
System.out.println("================================");
}
}
The input must be a string and a number
example input : Google 1
String.format("%15s",s) // pads left
String.format("%-15s",s) // pads right
Great summary here
import org.apache.commons.lang3.StringUtils;
String stringToPad = "10";
int maxPadLength = 10;
String paddingCharacter = " ";
StringUtils.leftPad(stringToPad, maxPadLength, paddingCharacter)
Way better than Guava imo. Never seen a single enterprise Java project that uses Guava but Apache String Utils is incredibly common.
You can also write a simple method like below
public static String padString(String str, int leng) {
for (int i = str.length(); i <= leng; i++)
str += " ";
return str;
}
The Guava Library has Strings.padStart that does exactly what you want, along with many other useful utilities.
Here's a neat trick:
// E.g pad("sss","00000000"); should deliver "00000sss".
public static String pad(String string, String pad) {
/*
* Add the pad to the left of string then take as many characters from the right
* that is the same length as the pad.
* This would normally mean starting my substring at
* pad.length() + string.length() - pad.length() but obviously the pad.length()'s
* cancel.
*
* 00000000sss
* ^ ----- Cut before this character - pos = 8 + 3 - 8 = 3
*/
return (pad + string).substring(string.length());
}
public static void main(String[] args) throws InterruptedException {
try {
System.out.println("Pad 'Hello' with ' ' produces: '"+pad("Hello"," ")+"'");
// Prints: Pad 'Hello' with ' ' produces: ' Hello'
} catch (Exception e) {
e.printStackTrace();
}
}
Here is the code with tests cases ;) :
#Test
public void testNullStringShouldReturnStringWithSpaces() throws Exception {
String fixedString = writeAtFixedLength(null, 5);
assertEquals(fixedString, " ");
}
#Test
public void testEmptyStringReturnStringWithSpaces() throws Exception {
String fixedString = writeAtFixedLength("", 5);
assertEquals(fixedString, " ");
}
#Test
public void testShortString_ReturnSameStringPlusSpaces() throws Exception {
String fixedString = writeAtFixedLength("aa", 5);
assertEquals(fixedString, "aa ");
}
#Test
public void testLongStringShouldBeCut() throws Exception {
String fixedString = writeAtFixedLength("aaaaaaaaaa", 5);
assertEquals(fixedString, "aaaaa");
}
private String writeAtFixedLength(String pString, int lenght) {
if (pString != null && !pString.isEmpty()){
return getStringAtFixedLength(pString, lenght);
}else{
return completeWithWhiteSpaces("", lenght);
}
}
private String getStringAtFixedLength(String pString, int lenght) {
if(lenght < pString.length()){
return pString.substring(0, lenght);
}else{
return completeWithWhiteSpaces(pString, lenght - pString.length());
}
}
private String completeWithWhiteSpaces(String pString, int lenght) {
for (int i=0; i<lenght; i++)
pString += " ";
return pString;
}
I like TDD ;)
Apache common lang3 dependency's StringUtils exists to solve Left/Right Padding
Apache.common.lang3 provides the StringUtils class where you can use the following method to left padding with your preferred character.
StringUtils.leftPad(final String str, final int size, final char padChar);
Here, This is a static method and the parameters
str - string needs to be pad (can be null)
size - the size to pad to
padChar the character to pad with
We have additional methods in that StringUtils class as well.
rightPad
repeat
different join methods
I just add the Gradle dependency here for your reference.
implementation 'org.apache.commons:commons-lang3:3.12.0'
https://mvnrepository.com/artifact/org.apache.commons/commons-lang3/3.12.0
Please see all the utils methods of this class.
https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html
GUAVA Library Dependency
This is from jricher answer. The Guava Library has Strings.padStart that does exactly what you want, along with many other useful utilities.
This code works great.
String ItemNameSpacing = new String(new char[10 - masterPojos.get(i).getName().length()]).replace('\0', ' ');
printData += masterPojos.get(i).getName()+ "" + ItemNameSpacing + ": " + masterPojos.get(i).getItemQty() +" "+ masterPojos.get(i).getItemMeasure() + "\n";
Happy Coding!!
public static String padString(String word, int length) {
String newWord = word;
for(int count = word.length(); count < length; count++) {
newWord = " " + newWord;
}
return newWord;
}
This simple function works for me:
public static String leftPad(String string, int length, String pad) {
return pad.repeat(length - string.length()) + string;
}
Invocation:
String s = leftPad(myString, 10, "0");
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
int s;
String s1 = sc.next();
int x = sc.nextInt();
System.out.printf("%-15s%03d\n", s1, x);
// %-15s -->pads right,%15s-->pads left
}
}
}
Use printf() to simply format output without using any library.