Search code examples
javastringreplacestring-length

Java: Filling a String up to a certain point


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);
}

Solution

  • 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 :).