简体   繁体   中英

Java padding a string read from a file

Ok so I have a file that reads integers, from a file that looks like this. 123456-1324563 .

The file reads these numbers as a string and I'm trying to figure out how to create a method that appends the number 0 to whichever side of the number being read is less than the other side.

For example if there are less numbers on the left side of the operator than on the right it would add 0's to the string so that the two numbers become even and return the new String. So I would need the method to turn a String like 123456789-123456 into 123456789-000123456 . But it would need to determine which side is shorter and pad 0's in front of it but still return the entire string.

Edit:

This is my most updated version of this method, that I'm using and when the + operator is passed in I'm getting an ArrayIndexOutOfBoundsException . But it works perfectly find with the - operator.

public String pad(String line, String operator){
    String str[] = line.split(Pattern.quote(operator));

    StringBuilder left = new StringBuilder(str[0]);
    StringBuilder right = new StringBuilder(str[1]);
    left = left.reverse();
    right = right.reverse();
    int len1 = left.length();
    int len2 = right.length();
    if(len1>len2){
        while(len1!=len2){
            right.append("0");
            len1--;
        }
    }else{
        while(len1!=len2){
            left.append("0");
            len2--;
        }
    }
    return left.reverse().toString()+operator+right.reverse().toString();
}

A simple solution:

public static String pad_num(String line){
    String[] groups = line.split("-");
    String left = groups[0],
            right = groups[1];

    if(left.length() < right.length()) {
        do {
            left = '0'+left;
        } while (left.length() < right.length());
    } else if(right.length() < left.length()) {
        do {
            right = '0'+right;
        } while (right.length() < left.length());
    }

    return left+'-'+right;
}

If you don't have fixed operator, you can pass it as an argument:

public static String pad_num(String line, String operator){
    //prevent ArrayIndexOutOfBoundsException
    if(!line.contains(operator)) {
        return line;
    }

    //prevent PatternSyntaxException by compiling it as literal
    String[] groups = Pattern.compile(operator, Pattern.LITERAL).split(line);

    //do the same
    ...

    return left+operator+right;
}

Using java 8 , more concise and compact version

public  String pad_num(String line, String operator){
    String str[] = line.split(Pattern.quote(operator));
    char []buff = new char[Math.abs(str[0].length()-str[1].length())];
    Arrays.fill(buff, '0');
    if(str[0].length()>str[1].length()){            
        return String.join(operator, str[0], new StringBuilder(String.valueOf(buff)).append(str[1]));
    }else{
        return String.join(operator, new StringBuilder(String.valueOf(buff)).append(str[0]), str[1]);
    }
}

If you don't have java8, use this implementation of your method

public  String pad_num(String line, String operator){
    String str[] = line.split(Pattern.quote(operator)); 
    StringBuilder left = new StringBuilder(str[0]);
    StringBuilder right = new StringBuilder(str[1]);
    left = left.reverse();
    right = right.reverse();
    int len1 = left.length();
    int len2 = right.length();
    if(len1>len2){
        while(len1!=len2){
            right.append("0");
            len1--;
        }
    }else{
        while(len1!=len2){
            left.append("0");
            len2--;
        }
    }
    return left.reverse().toString()+operator+right.reverse().toString();

}

And call those method as

String result = pad_num("123456+1324563", "+");
String result = pad_num("123456-1324563", "-");

Edit:

Reason of ArrayIndexOutOfBoundsException is method calling with mismatch arguments like

pad_num("123456-1324563", "+");   // - in line and + in operator

or

pad_num("123456+1324563", "-");   // + in line and - in operator

You can do this:

public String pad_num(String line){
        String[] lines = line.split("-");
        String s1=lines[0];
        String s2=lines[1];
        StringBuilder sb = new StringBuilder();
        if(s1.length() == s2.length()){
            return line;
        }else if(s1.length() > s2.length()){
            sb.append(s1);
            sb.append("-");
            for(int i=0;i<s1.length()-s2.length();i++){
                //add zeros before s2
                sb.append("0");
            }
            sb.append(s2);
        }else{
            for(int i=0;i<s2.length()-s1.length();i++){
                //add zeros before s1
                sb.append("0");
            }
            sb.append(s1);
            sb.append("-");
            sb.append(s2);
        }
    return sb.toString();
}

The given solutions work. Just an alternate one using Apache StringUtils.

public static String pad_num(String line){
    String paddedStr = null;
    String[] numbers = StringUtils.split(line, "-");
    if(numbers == null || (numbers[0].length() == numbers[1].length())) {
        return line;
    }

    if(numbers[0].length() > numbers[1].length()) {
        paddedStr = numbers[0] + "-" + StringUtils.leftPad(numbers[1], numbers[0].length(), "0");
    } else {
        paddedStr = StringUtils.leftPad(numbers[0], numbers[1].length(), "0") + "-" + numbers[1];
    }
    return paddedStr;
}

In "real life" (assuming this is not homework), you should use a library for the purpose. For example, using Guava's Strings.padStart() , the method simplifies into:

import static com.google.common.base.Strings.padStart;
/* ... */
public String pad(String line, String delim, char padding) {

    String[] tokens = line.split(delim);
    int[] lengths = new int[] {tokens[0].length(), tokens[1].length()};

    return lengths[0] > lengths[1] 
            ? tokens[0] + delim + padStart(tokens[1], lengths[0], padding)

                : lengths[0] < lengths[1]
                    ? padStart(tokens[0], lengths[1], padding) + delim + tokens[1]

                             : line;
}

Some test runs with the code

System.out.println(pad("123456-1324563", "-", '0'));
System.out.println(pad("1324563-123456", "-", '0'));
System.out.println(pad("123456789-123456", "-", '0'));
System.out.println(pad("123456-123456", "-", '0'));

yield

0123456-1324563
1324563-0123456
123456789-000123456
123456-123456

As others have already told you, use a lib for this ( Guava / Apache StringUtils ).

Yet another example of how to do this manually, should you insist:

String pad(String s) {
    String[] parts = s.split("-");
    int n = parts[0].length() - parts[1].length();
    return n < 0
            ? String.format("%s%s-%s", zeros(Math.abs(n)), parts[0], parts[1])
            : String.format("%s-%s%s", parts[0], zeros(Math.abs(n)), parts[1]);
}

(And here is that zeros-util...)

String zeros(int numZeros) {
    char[] chars = new char[numZeros];
    Arrays.fill(chars, '0');
    return new String(chars);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM