在.net中有一个padLeft(int totalWidth, String paddingChar);
比如:String s = "FF";
s.padLeft(4,"0"); //S的结果为00FF
但在Java中padLeft(String str, int Size);
比如:String s = "FF";
padLeft(s, 4); //结果为" FF"
前面不足位自动用空格补齐的。
如果我想用JAVA实现用0补齐该如何实现呢?即第一个S的结果。
------解决方案--------------------
- Java code
String padLeft(String s, int length) { byte[] bs = new byte[length]; byte[] ss = s.getBytes(); Arrays.fill(bs, (byte) (48 & 0xff)); System.arraycopy(ss, 0, bs,length - ss.length, ss.length); return new String(bs); }
------解决方案--------------------
自己写一个方法吧:
- Java code
import java.util.*;public class test{ public static void main(String[] args) { String s = "FF"; System.out.println(padLeft(s,8)); } public static String padLeft(String str,int len){ String pad="0000000000000000"; return len>str.length()&&len<=16&&len>=0?pad.substring(0,len-str.length())+str:str; }}
------解决方案--------------------
private static String fill(String input, int size, char symbol) {
while (input.length() < size) {
input = symbol + input;
}
return input;
}
------解决方案--------------------
- Java code
public static String pad (String str ,int size ,boolean isprefixed) { if (str == null) str = ""; int str_size = str.length(); int pad_len = size - str_size; StringBuffer retvalue = new StringBuffer(); for (int i = 0; i < pad_len; i++) { retvalue.append("0"); } if (isprefixed) return retvalue.append(str).toString(); return retvalue.insert(0, str).toString(); }