English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Implementation code of Java String string padding with zeros or spaces

No more chatter, the key code is as follows:

package cn.com.songjy;
import java.text.NumberFormat;
//Left-zero-padding of numbers in Java
public class NumberFormatTest {
public static void main(String[] args) {
// Data to be tested
int i = 1;
// Get an instance of NumberFormat
NumberFormat nf = NumberFormat.getInstance();
// Set whether to use grouping
nf.setGroupingUsed(false);
// Set the maximum number of integer digits
nf.setMaximumIntegerDigits(4);
// Set the minimum number of integer digits
nf.setMinimumIntegerDigits(4);
// Output test statement
System.out.println(nf.format(i));
}
}
/** 
* Implementation of automatic zero-padding before converting numbers to strings in Java. 
* 
*/ 
public class TestStringFormat { 
public static void main(String[] args) { 
int youNumber = 1; 
// 0 represents the front supplement 0 
// 4 represents the length of4 
// d represents the parameter as a positive number type 
String str = String.format("%04d", youNumber); 
System.out.println(str); // 0001 
} 
}
//The serial number plus1After returning, the length of the serial number is4
private static final String STR_FORMAT = "0000"; 
public static String haoAddOne_2(String liuShuiHao){
Integer intHao = Integer.parseInt(liuShuiHao);
intHao++;
DecimalFormat df = new DecimalFormat(STR_FORMAT);
return df.format(intHao);
}

Well, the above code is about the implementation of Java String string padding 0 or space, very good, hope it can be helpful to everyone, if you have any questions, please leave me a message, the editor will reply to everyone in time, and here I also want to thank everyone for their support for the YANHUA tutorial website!

You May Also Like