1

I am trying to convert the following code which is in c# to java. And I am facing difficulty in converting it. Please can anyone suggest me a simple way to do it in Java.

 if (Password.Length <= 8)
            Password = Password.PadRight(8);
        else
            Password = Password.PadRight(20);
Farheen
  • 169
  • 2
  • 2
  • 11
  • you can use StringUtils or if your string only contains integer then you can use string format as well by parsing string into inetger – Abu Sufian Nov 21 '16 at 11:39

2 Answers2

2

You won't be able to modify the methods that are built into the String class, so instead I think it's best to write static utility methods to reproduce the behaviour of the C# methods.

The code might look something like this (though be sure to write your own unit tests before using these methods, or any other methods you write or introduce).

public static void main(String[] args) {
    String original = "text";
    int padToLength = 10;
    System.out.println("Padded:\n'" + padRight(original, padToLength) + "'");
    System.out.println("Padded:\n'" + padRight(original, padToLength, '@')
            + "'");
}

public static String padRight(String original, int padToLength) {
    return padRight(original, padToLength, ' ');
}

public static String padRight(String original, int padToLength, char padWith) {
    if (original.length() >= padToLength) {
        return original;
    }
    StringBuilder sb = new StringBuilder(padToLength);
    sb.append(original);
    for (int i = original.length(); i < padToLength; ++i) {
        sb.append(padWith);
    }
    return sb.toString();
}

This will output to the console:

Padded with spaces:
'text      '
Padded with custom character:
'text@@@@@@'
Bobulous
  • 12,241
  • 4
  • 36
  • 63
1

You may use Apache String util for padding (readymade! solution)

https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#rightPad-java.lang.String-int-

Or you can use string format

Password = String.format("%20s", Password); in place of Password = Password.PadRight(20);

and Password = String.format("%8s", Password); in place of Password = Password.PadRight(8);

The Mighty Programmer
  • 1,047
  • 10
  • 21