0

I am working on a project but I am stuck at one point. I want the result string always to be 128 characters long. When my String is shorter, I want to replace it with "0"s. I tried many ways but none of them worked so I decided to ask it here.

This is something I have tried:

String s = "This is a String!";
if(s.length() < 128){
    s.replace(s.length(), 128, "0");
    System.out.println(s);
}
mmking
  • 1,278
  • 4
  • 21
  • 33
fihdi
  • 135
  • 1
  • 12

3 Answers3

0

If you wanted your short String right-padded with zeros:

String s = "SomeTestString!";
if(s.length() < 128) {
   s = String.format("%-128s", s ).replace(' ', '0');
} else {
   s = s.substring(0,128);
}
System.out.println(s);

If you wanted your short String replaced with zeros:

String s = "SomeTestString!";
if(s.length() < 128) {
   s = s.replace(s.length(), 128, "0");
} else {
   s = s.substring(0,128) ;
}
System.out.println(s);

If you wanted short String to have 128 chars '0':

StringBuffer buf = new StringBuffer(128);
for (int i = 0; i < 128; i++) {
   buf.append("0");
}
System.out.println(buf);

Yeah, at least I practiced a bit :).

TheMP
  • 7,637
  • 9
  • 37
  • 69
0
String s = "This is a String!";
if(s.length() < 128){
   while (s.length <= 128){
      s += "0";
   }
   System.out.println(s);
}
  • 2
    While this will work it will also create many new String instances (see [Immutabilety](http://stackoverflow.com/questions/1552301/immutability-of-strings-in-java)). A `StringBuffer` or `StringBuilder` is to be preferred. – Dawnkeeper Jun 11 '14 at 19:23
0

Here's one way to right pad a String.

public class Snippet {

    public static void main(String[] args) {
        int length = 128;
        String s = "This is a String!";
        System.out.println(new Snippet().rightPadString(s, length, '0'));
    }

    public String rightPadString(String s, int length, char c) {
        if (s.length() < length) {
            StringBuilder builder = new StringBuilder(length);
            builder.append(s);
            for (int i = s.length(); i < length; i++) {
                builder.append(c);
            }
            s = builder.toString();
        } else {
            s = s.substring(0, length);
        }
        return s;
    }
}
Gilbert Le Blanc
  • 45,374
  • 5
  • 61
  • 107