Comparez les prix des domaines et des services informatiques des vendeurs du monde entier

Remplir une chaîne avec des zéros à gauche

J'ai vu des questions similaires
https://coderoad.ru/388461/
et
https://coderoad.ru/473282/
.

Mais je ne comprends pas comment laisser une chaîne avec zéro.

entrée: "129018"
sortir: "0000129018"

La longueur totale de sortie devrait être TEN.
Invité:

Hannah

Confirmation de:

Si votre ligne ne contient que des chiffres, vous pouvez en créer un entier, puis remplir:


String.format/"0d", Integer.parseInt/mystring//;


Sinon, alors
https://coderoad.ru/4421400/
.

Darius

Confirmation de:

String paddedString = org.apache.commons.lang.StringUtils.leftPad/"129018", 10, "0"/


Le deuxième paramètre est la longueur de sortie souhaitée

"0"- C'est le symbole de remplissage

Conrad

Confirmation de:

Cela conduira au fait que n'importe quelle chaîne aura une largeur totale. 10, Ne vous inquiétez pas des erreurs d'analyse de la syntaxe:


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

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


Si tu veux pad à droite:


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

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


Vous pouvez remplacer les caractères. " # "Tout symbole que vous souhaitez ajouter, répétant le nombre de fois que vous souhaitez que la largeur de la ligne globale soit égale. E.g. Si vous voulez ajouter des zéros sur la gauche afin que toute la chaîne soit longue 15 Symboles:


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

//unpadded is "12345"
//padded is "000000000012345"


L'avantage de cela par rapport à la réponse du Hichik est qu'il n'utilise pas Integer.parseInt, Qu'est-ce qui peut causer une exception /Par exemple, si le numéro que vous souhaitez ajouter est trop grand, comme 12147483647/. L'inconvénient est que si ce que vous remplissez, est déjà int, Vous devrez le convertir à la chaîne et à l'arrière, ce qui est indésirable.

Donc, si vous savez exactement ce que c'est int, La réponse de la randonnée fonctionne bien. Sinon, il s'agit d'une stratégie possible.

Hippolite

Confirmation de:

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//;

David

Confirmation de:

String str = "129018";
String str2 = String.format/"s", str/.replace/' ', '0'/;
System.out.println/str2/;

Blanche

Confirmation de:

vous pouvez utiliser apache commons StringUtils


StringUtils.leftPad/"129018", 10, "0"/;


https://commons.apache.org/pro ... tring,%20int,%20char/
/

Alice

Confirmation de:

Utilisez une chaîne pour formater


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/;

}
}


Conclusion: String: 00000wrwer

Où le premier argument - Il s'agit d'une chaîne à formatée, la deuxième longueur d'argumentation de la longueur de sortie souhaitée et le troisième symbole d'argument que la chaîne doit être complété.

Utilisez le lien de téléchargement jar
[url=http://commons.apache.org/proper/commons-lang/download_lang.cgi]http://commons.apache.org/prop ... g.cgi[/url]

Ernest

Confirmation de:

Si vous avez besoin de performances et que vous connaissez la taille de la chaîne maximale, utilisez-la:


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


Rappelez-vous la taille de la ligne maximale. Si c'est plus grand que la taille StringBuffer, Tu auras
java.lang.StringIndexOutOfBoundsException

.

Francois

Confirmation de:

Vieille question, mais j'ai aussi deux méthodes.

Pour /Prédéfini/ Longueur:


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


Pour la longueur variable:


public static String fill/String text, int size/ {
StringBuilder builder = new StringBuilder/text/;
while /builder.length// < size/ {
builder.append/'0'/;
}
return builder.toString//;
}

Fabien

Confirmation de:

Utilisation
https://code.google.com/p/guava-libraries/
:

Maven

:


<dependency>
<artifactid>guava</artifactid>
<groupid>com.google.guava</groupid>
<version>14.0.1</version>
</dependency>


Code

:


Strings.padStart/"129018", 10, '0'/ returns "0000129018"

Ernest

Confirmation de:

Je préfère ce code:


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


et alors:


System.out.println/StrMgr.leftPad/"hello", 20, "x"//; 
System.out.println/StrMgr.rightPad/"hello", 20, "x"//;

Dominique

Confirmation de:

Basé sur

@Haroldo Macêdo , J'ai créé une méthode dans ma classe d'utilisateurs
Utils

, par exemple


/**
* 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;
}


Puis appelez
Utils.padLeft/str, 10, "0"/;

Constantine

Confirmation de:

Voici une autre approche:


int pad = 4;
char[] temp = /new String/new char[pad]/ + "129018"/.toCharArray//
Arrays.fill/temp, 0, pad, '0'/;
System.out.println/temp/

Gregoire

Confirmation de:

Voici ma décision:


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++, +="" 00000101="" ;="" ;[="" <="" code]="" div="" s="" sortir:="" system.out.println="">
<div class="answer_text">
Joint droit avec longueur fixe-10:
String.format/"%1$-10s", "abc"/
Joint de gauche avec longueur fixe-10:
String.format/"%1$10s", "abc"/
</div>
<div class="answer_text">
Voici une solution basée sur String.format, qui fonctionnera pour les chaînes et convient à une longueur variable.


[code]public static String PadLeft/String stringToPad, int padToLength/{
String retValue = null;
if/stringToPad.length// &lt; 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/ + "'"/;
}


Sortir:

'000000test'
'test'
'test'
'0test'
</div>
<div class="answer_text">
La solution Satish est très bonne parmi les réponses attendues. Je voulais le rendre plus général en ajoutant une variable n dans la chaîne de format à la place 10 Symboles.


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


Cela fonctionnera dans la plupart des situations
</div>
<div class="answer_text">

int number = -1;
int holdingDigits = 7;
System.out.println/String.format/"%0"+ holdingDigits +"d", number//;


Il suffit de demander à ce sujet dans une interview ........

Ma réponse est plus bas mais elle /susmentionné/ Beaucoup plus agréable-&gt;


String.format/"d", num/;


Ma réponse est:


static String leadingZeros/int num, int digitSize/ {
//test for capacity being too small.

if /digitSize &lt; 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 &lt; digitSize; i++/ {
sb.append/"0"/;
}
sb.append/String.valueOf/num//;
return sb.substring/sb.length// - digitSize, sb.length///;
}
}


</div>
<div class="answer_text">
Consultez mon code qui fonctionnera pour des entiers et des lignes.

Supposons notre premier numéro-129018. Et nous voulons ajouter à ces zéros de sorte que la longueur de la ligne finale était be 10. Pour ce faire, vous pouvez utiliser le code suivant.


int number=129018;
int requiredLengthAfterPadding=10;
String resultString=Integer.toString/number/;
int inputStringLengh=resultString.length//;
int diff=requiredLengthAfterPadding-inputStringLengh;
if/inputStringLengh<requiredlengthafterpadding "0"="" "\0",="" +number;="" .replace="" ;[="" <="" char[diff]="" code]="" div="" new="" resultstring="" string="" system.out.println="" {="" }="">
<div class="answer_text">
Je l'ai utilisé:


[code]DecimalFormat numFormat = new DecimalFormat/"00000"/;
System.out.println/"Code format: "+numFormat.format/123//;


Résultat: 00123

J'espère que tu trouves cela utile!
</div>
</requiredlengthafterpadding></div></p-j;g++,>

David

Confirmation de:

Joint droit avec longueur fixe-10:
String.format/"%1$-10s", "abc"/
Joint de gauche avec longueur fixe-10:
String.format/"%1$10s", "abc"/

Emmanuel

Confirmation de:

Voici une solution basée sur String.format, qui fonctionnera pour les chaînes et convient à une longueur variable.


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/ + "'"/;
}


Sortir:

'000000test'
'test'
'test'
'0test'

Emile

Confirmation de:

La solution Satish est très bonne parmi les réponses attendues. Je voulais le rendre plus général en ajoutant une variable n dans la chaîne de format à la place 10 Symboles.


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


Cela fonctionnera dans la plupart des situations

Enzo

Confirmation de:

int number = -1;
int holdingDigits = 7;
System.out.println/String.format/"%0"+ holdingDigits +"d", number//;


Il suffit de demander à ce sujet dans une interview ........

Ma réponse est plus bas mais elle /susmentionné/ Beaucoup plus agréable->


String.format/"d", num/;


Ma réponse est:


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

Clement

Confirmation de:

Consultez mon code qui fonctionnera pour des entiers et des lignes.

Supposons notre premier numéro-129018. Et nous voulons ajouter à ces zéros de sorte que la longueur de la ligne finale était be 10. Pour ce faire, vous pouvez utiliser le code suivant.


int number=129018;
int requiredLengthAfterPadding=10;
String resultString=Integer.toString/number/;
int inputStringLengh=resultString.length//;
int diff=requiredLengthAfterPadding-inputStringLengh;
if/inputStringLengh<requiredlengthafterpadding "0"="" "\0",="" +number;="" .replace="" ;[="" <="" char[diff]="" code]="" div="" new="" resultstring="" string="" system.out.println="" {="" }="">
<div class="answer_text">
Je l'ai utilisé:


[code]DecimalFormat numFormat = new DecimalFormat/"00000"/;
System.out.println/"Code format: "+numFormat.format/123//;


Résultat: 00123

J'espère que tu trouves cela utile!
</div>
</requiredlengthafterpadding>

Catherine

Confirmation de:

Je l'ai utilisé:


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


Résultat: 00123

J'espère que tu trouves cela utile!

Pour répondre aux questions, connectez-vous ou registre