Left padding a String with Zeros [duplicate]

To pytanie ma już odpowiedź tutaj:

Widziałem podobne pytania tutaj i tutaj .

Ale nie rozumiem jak zostawić Pad ciąg z Zero.

Input: "129018" output: "0000129018"

Całkowita długość wyjścia powinna wynosić dziesięć.

Author: Community, 2010-12-17

20 answers

Jeśli twój łańcuch zawiera tylko liczby, możesz zrobić z niego liczbę całkowitą, a następnie wykonać wypełnienie:

String.format("%010d", Integer.parseInt(mystring));

Jeśli nie chciałbym wiedzieć, jak można to zrobić .

 300
Author: khachik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:34:47
String paddedString = org.apache.commons.lang.StringUtils.leftPad("129018", 10, "0")

Drugi parametr to żądana długość wyjścia

"0" jest znakiem padding

 127
Author: Oliver Michels,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-21 13:03:07

Spowoduje to pozostawienie dowolnego ciągu do całkowitej szerokości 10 bez martwienia się o błędy parsowania:

String unpadded = "12345"; 
String padded = "##########".substring(unpadded.length()) + unpadded;

//unpadded is "12345"
//padded   is "#####12345"

Jeśli chcesz pad prawo:

String unpadded = "12345"; 
String padded = unpadded + "##########".substring(unpadded.length());

//unpadded is "12345"
//padded   is "12345#####"  

Możesz zastąpić znaki " # " dowolnym znakiem, który chcesz wstawić, powtarzając ilość razy, jaką chcesz, aby całkowita Szerokość łańcucha była. Np. jeśli chcesz dodać zera po lewej stronie, aby cały łańcuch miał długość 15 znaków:

String unpadded = "12345"; 
String padded = "000000000000000".substring(unpadded.length()) + unpadded;

//unpadded is "12345"
//padded   is "000000000012345"  
[[3]] korzyść z tego nad odpowiedzią chaczika jest taka, że to nie używaj Integer.parseInt, który może rzucić wyjątek (na przykład, jeśli liczba, którą chcesz wstawić jest zbyt duża, jak 12147483647). Wadą jest to, że jeśli to, co padding jest już int, to będziesz musiał przekonwertować go na ciąg i z powrotem, co jest niepożądane.

Więc, jeśli wiesz na pewno, że to int, odpowiedź khachika działa świetnie. Jeśli nie, to jest to możliwa strategia.

 92
Author: Rick Hanlon II,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-29 12:40:13
String str = "129018";
StringBuilder sb = new StringBuilder();

for (int toPrepend=10-str.length(); toPrepend>0; toPrepend--) {
    sb.append('0');
}

sb.append(str);
String result = sb.toString();
 47
Author: thejh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-03-03 11:40:16
String str = "129018";
String str2 = String.format("%10s", str).replace(' ', '0');
System.out.println(str2);
 41
Author: Satish,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-05-25 20:29:51

Możesz używać Apache commons StringUtils

StringUtils.leftPad("129018", 10, "0");

Http://commons.apache.org/lang/api-2.3/org/apache/commons/lang/StringUtils.html

 13
Author: thk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-08-15 11:00:17

Aby sformatować Łańcuch użyj

import org.apache.commons.lang.StringUtils;

public class test {

    public static void main(String[] args) {

        String result = StringUtils.leftPad("wrwer", 10, "0");
        System.out.println("The String : " + result);

    }
}

Output: the String: 00000wrwer

Gdzie pierwszym argumentem jest łańcuch, który ma być sformatowany, drugim argumentem jest długość żądanej długości wyjściowej, a trzecim argumentem jest znak, za pomocą którego łańcuch ma być wypełniony.

Użyj linku, aby pobrać jar http://commons.apache.org/proper/commons-lang/download_lang.cgi

 13
Author: Nagarajan S R,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-10 15:09:19

Jeśli potrzebujesz wydajności i znasz maksymalny rozmiar łańcucha użyj tego:

String zeroPad = "0000000000000000";
String str0 = zeroPad.substring(str.length()) + str;

Należy pamiętać o maksymalnym rozmiarze łańcucha. Jeśli jest większy niż rozmiar StringBuffer, otrzymasz java.lang.StringIndexOutOfBoundsException.

 10
Author: Haroldo Macedo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-23 10:29:40

Stare pytanie, ale mam też dwie metody.


Dla stałej (predefiniowanej) długości:

    public static String fill(String text) {
        if (text.length() >= 10)
            return text;
        else
            return "0000000000".substring(text.length()) + text;
    }

Dla zmiennej długości:

    public static String fill(String text, int size) {
        StringBuilder builder = new StringBuilder(text);
        while (builder.length() < size) {
            builder.append('0');
        }
        return builder.toString();
    }
 4
Author: Carlos Heuberger,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-05-25 21:05:41

Użyj Google Guava :

Maven:

<dependency>
     <artifactId>guava</artifactId>
     <groupId>com.google.guava</groupId>
     <version>14.0.1</version>
</dependency>

Przykładowy kod:

Strings.padStart("129018", 10, '0') returns "0000129018"  
 4
Author: ThoQ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-10 12:29:24

Oto inne podejście:

int pad = 4;
char[] temp = (new String(new char[pad]) + "129018").toCharArray()
Arrays.fill(temp, 0, pad, '0');
System.out.println(temp)
 2
Author: nullpotent,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-19 17:38:55

Oto moje rozwiązanie:

String s = Integer.toBinaryString(5); //Convert decimal to binary
int p = 8; //preferred length
for(int g=0,j=s.length();g<p-j;g++, s= "0" + s);
System.out.println(s);

Wyjście: 00000101

 2
Author: Sherwin Pitao,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-24 07:30:48

Wyściółka prawa o długości fix-10: Sznurek.format ("%1$ - 10s", " abc") Lewa wyściółka o długości fix-10: Sznurek.format ("%1$10s","abc")

 1
Author: Arun,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-11-20 23:22:44

Rozwiązanie przez Satish jest bardzo dobre wśród oczekiwanych odpowiedzi. Chciałem uczynić go bardziej ogólnym, dodając zmienną n do formatu string zamiast 10 znaków.

int maxDigits = 10;
String str = "129018";
String formatString = "%"+n+"s";
String str2 = String.format(formatString, str).replace(' ', '0');
System.out.println(str2);

To zadziała w większości sytuacji

 1
Author: Prabhu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-02 04:30:28

Na podstawie odpowiedzi @ Haroldo Macêdo , stworzyłem metodę w mojej klasie custom Utils, taką jak

/**
 * Left padding a string with the given character
 *
 * @param str     The string to be padded
 * @param length  The total fix length of the string
 * @param padChar The pad character
 * @return The padded string
 */
public static String padLeft(String str, int length, String padChar) {
    String pad = "";
    for (int i = 0; i < length; i++) {
        pad += padChar;
    }
    return pad.substring(str.length()) + str;
}

Następnie wywołaj Utils.padLeft(str, 10, "0");

 1
Author: Sithu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:26:37
    int number = -1;
    int holdingDigits = 7;
    System.out.println(String.format("%0"+ holdingDigits +"d", number));
Pytałem o to w wywiadzie........

Moja odpowiedź poniżej, ale ta (wspomniana wyżej) jest o wiele ładniejsza- >

String.format("%05d", num);

Moja odpowiedź brzmi:
static String leadingZeros(int num, int digitSize) {
    //test for capacity being too small.

    if (digitSize < String.valueOf(num).length()) {
        return "Error : you number  " + num + " is higher than the decimal system specified capacity of " + digitSize + " zeros.";

        //test for capacity will exactly hold the number.
    } else if (digitSize == String.valueOf(num).length()) {
        return String.valueOf(num);

        //else do something here to calculate if the digitSize will over flow the StringBuilder buffer java.lang.OutOfMemoryError 

        //else calculate and return string
    } else {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < digitSize; i++) {
            sb.append("0");
        }
        sb.append(String.valueOf(num));
        return sb.substring(sb.length() - digitSize, sb.length());
    }
}
 0
Author: bockymurphy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-26 14:50:17

Sprawdź mój kod, który będzie działał dla integer i String.

Załóżmy, że nasza pierwsza liczba to 129018. I chcemy dodać do tego zera, aby długość ostatniego ciągu wynosiła 10. W tym celu możesz użyć następującego kodu

    int number=129018;
    int requiredLengthAfterPadding=10;
    String resultString=Integer.toString(number);
    int inputStringLengh=resultString.length();
    int diff=requiredLengthAfterPadding-inputStringLengh;
    if(inputStringLengh<requiredLengthAfterPadding)
    {
        resultString=new String(new char[diff]).replace("\0", "0")+number;
    }        
    System.out.println(resultString);
 0
Author: Fathah Rehman P,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-24 10:31:15

Oto rozwiązanie oparte na łańcuchu.format, który będzie działał dla ciągów i nadaje się do zmiennej długości.

public static String PadLeft(String stringToPad, int padToLength){
    String retValue = null;
    if(stringToPad.length() < padToLength) {
        retValue = String.format("%0" + String.valueOf(padToLength - stringToPad.length()) + "d%s",0,stringToPad);
    }
    else{
        retValue = stringToPad;
    }
    return retValue;
}

public static void main(String[] args) {
    System.out.println("'" + PadLeft("test", 10) + "'");
    System.out.println("'" + PadLeft("test", 3) + "'");
    System.out.println("'" + PadLeft("test", 4) + "'");
    System.out.println("'" + PadLeft("test", 5) + "'");
}

Wyjście: "000000test" "test" "test" "0test"

 0
Author: P.V.M. Kessels,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-29 07:25:09

Wolę ten kod:

public final class StrMgr {

    public static String rightPad(String input, int length, String fill){                   
        String pad = input.trim() + String.format("%"+length+"s", "").replace(" ", fill);
        return pad.substring(0, length);              
    }       

    public static String leftPad(String input, int length, String fill){            
        String pad = String.format("%"+length+"s", "").replace(" ", fill) + input.trim();
        return pad.substring(pad.length() - length, pad.length());
    }
}

A następnie:

System.out.println(StrMgr.leftPad("hello", 20, "x")); 
System.out.println(StrMgr.rightPad("hello", 20, "x"));
 0
Author: Ariel Giomi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-15 01:42:46

Użyłem tego:

DecimalFormat numFormat = new DecimalFormat("00000");
System.out.println("Code format: "+numFormat.format(123));

Wynik: 00123

Mam nadzieję, że okaże się to przydatne!

 -1
Author: Carlos Muñoz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-15 02:30:20