-3

So my problem was such that I had to compute 10^n such that n ~ 10^5. Obviously it wouldn't fit in any data type hence I decided to use a string instead. Finally, I did find the solution in the beginners book https://beginnersbook.com/2014/07/java-right-padding-a-string-with-spaces-and-zeros/.

I don't want the BigInteger solution of multiplying 10 n times.

public class PadRightExample2 {
    public static void main(String[] argv) {
        System.out.println("#" + rightPadZeros("mystring", 10) + "@");
        System.out.println("#" + rightPadZeros("mystring", 15) + "@");
        System.out.println("#" + rightPadZeros("mystring", 20) + "@");
    }

    public static String rightPadZeros(String str, int num) {
        return String.format("%1$-" + num + "s", str).replace(' ', '0');
    }
}

Output:

#mystring00@
#mystring0000000@
#mystring000000000000@

Can anybody explain what is %1$- and what is s used for ?

Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
  • 5
    Possible duplicate of [Understanding the $ in Java's format strings](https://stackoverflow.com/questions/1915074/understanding-the-in-javas-format-strings) – ech0 Jul 14 '18 at 11:37
  • I didn't understand after going through that that's why I asked . – Sushant Pradhan Jul 14 '18 at 11:42
  • I'll highly appreciate if somebody answers this :) – Sushant Pradhan Jul 14 '18 at 11:43
  • 1
    Did you try reading the [documentation](https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html) regarding the formatter? – ech0 Jul 14 '18 at 11:45
  • 2
    `Obviuosly it wouldn't fit in any data type` - this is wrong. Use [BigDecimal](https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html) for numbers of any size. – Robert Jul 14 '18 at 11:50
  • @Robert Best answer off all! BigDecimal will get as large as you'd like (Until your computer/JVM doesn't run out of memory of course)... You should provide this as answer... Somebody should up vote your comment! – 0x1C1B Jul 14 '18 at 11:55
  • @0x1C1B Except that OP want a result like `#mystring0000000@` and `BigDecimal`/`BigInteger` cannot help build that. I mean, Robert is right, `BigDecimal` can be used numbers of any size, but `0000000` is not "a number of any size", since numbers in computers don't have a defined number of leading zeroes. – Andreas Jul 14 '18 at 12:05
  • @Andreas Sure but if I understand him right, he just use this because of "no data type would fit" the size of his calculation and that's wrong there is an easier way just use `BigDecimal` and prevent this elaborate and "error-prone" string calculation or Does I understand him wrong? – 0x1C1B Jul 14 '18 at 12:08
  • @0x1C1B Yes, you understand wrong, so let me ask you: How would you implement `rightPadZeros("mystring", 15)` to return `mystring0000000` using `BigDecimal`? Because that is what OP wants. – Andreas Jul 14 '18 at 12:11
  • @Andreas Yea sure you're right! But I'm sure @Robert wasn't intend to solve the string calculation issue, instead he tried to prevent a elaborate string calculation and solve it in a more efficient way (And you wouldn't deny that `BigDecimal` is the easier way or?)... If you strict try to answer the original question than of course `BigDecimal` isn't a fitting answer you're right – 0x1C1B Jul 14 '18 at 12:15
  • @0x1C1B Which was my point in commenting your comment for Robert to write it as an answer. Robert was appropriately commenting that *"wouldn't fit in any data type"* is an incorrect statement, since `BigDecimal` can do that, but `BigDecimal` is not a solution for the problem, and hence is not an answer to the question, so your suggestion to write it as an answer was misguided. – Andreas Jul 14 '18 at 12:21
  • @Andreas Last statement: The devil is in the detail. You're right it was a good improvement but **not** a fitting answer – 0x1C1B Jul 14 '18 at 12:23
  • I stand corrected . BigDecimal/BigInteger can be used but for this particular case I want to avoid it .I wanted sth which could do the thing in one line . Like I've posted above. – Sushant Pradhan Jul 14 '18 at 14:09

2 Answers2

1
  • % stands for the format of String
  • 1$ means the first additional parameter args of String.format(String format, Object... args), 2$ would be the second one, etc..
  • - is the left justification, in connection with number declares the length of the final output, briefly said. The documentation of java.util.Formatter explains is a bit better:

    Left justifies the output. Spaces ('\u0020') will be added at the end of the converted value as required to fill the minimum width of the field.

  • s stands for the String parameter type

The typical example is logging, where you parse the arguments with %s which is practically the same. With a dollar character and number %1$s you specify the argument number and -10 makes the final output length of 10.

#mystring00@            // mystring00 has length 10
#mystring0000000@       // mystring0000000 has length 15
#mystring000000000000@  // #mystring000000000000 has length 20

Most of the information could be found in the documentation of java.util.Formatter, which is used within String::format.


The snippet you have found might be a bit confusing because it works even without 1$ because the arguments are passed in order.

Try the following: String.format("%2$-" + num + "s", str, "test").replace(' ', '0');. The result will be

#test000000@
#test00000000000@
#test0000000000000000@

Whereas String.format("%1$-" + num + "s", str, "test").replace(' ', '0'); leads to the original result from your snippet. Notice the 1$ and 2$ difference.

Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
-1

Maybe I'm not understanding the question correctly, but cant you do:

public static String rightPadZeros(String str, int num) {
    String add = "";
    for(int i = 0; i < num;i++) add += "0";
    return str + add;
}

I dont quite understand why you would want two zeros when num=10, but if you want that, do:

public static String rightPadZeros(String str, int num) {
    String add = "";
    for(int i = 0; i < num - 8;i++) add += "0";
    return str + add;
}

EDIT: apparenetely that was bad for performance, so this might be better:

public static String rightPadZeros(String str, int num) {
    return str + new String(new char[num]).replace("\0", "0");
}
Pieter Mantel
  • 123
  • 1
  • 9