public class StringManager {
/**
* 将字符串转为字母串
* @param str
* @return
*/
public String changeToLetter(String str){
String result = "";
String[] arr = new String[]{"A","B","C","D","E","F","G","H","I","J"};
for(int i = 0; i<str.length(); i++){
if(Character.isDigit(str.charAt(i))){
result += arr[Integer.parseInt(String.valueOf(str.charAt(i)))];
}else{
result += str.charAt(i);
}
}
return result;
}
/**
* 根据输入的字符串,获取字符串中的数字,并得到天数
* @param str
* @return
*/
public Integer getDaysFromString(String str){
int year = 0;
int month = 0;
int day = 0;
int result = 0;
String daystrtemp = "0";
for(int i=0; i<str.length(); i++){
char temp1 = str.charAt(i);
String temp = String.valueOf(temp1);
if(Character.isDigit(temp1)){
daystrtemp += temp;
}else{
//遇到的单位是 年
if("年".equals(temp)){
year = Integer.valueOf(daystrtemp);
//算得总天数
year = year*365;
}else if((i+1)<str.length() && "个".equals(temp) && "月".equals(String.valueOf(str.charAt(i+1)))){
//遇到的单位是 个月
month = Integer.valueOf(daystrtemp);
//算得总天数
month = month*30;
}else if("日".equals(temp) || "天".equals(temp)){
//遇到的单位是 天
day = Integer.valueOf(daystrtemp);
}
daystrtemp = "0";
}
}
result += year + month + day;
return result;
}
/**
* 根据数字和位数进行补位,位数不足补0
* @param num 原始数字
* @param ws 需要生成的位数
* @return
*/
public String fillzero(Long num,int ws){
String formatstr = "";
for(int i=0;i<ws;i++){
formatstr += "0";
}
java.text.DecimalFormat df = new java.text.DecimalFormat(formatstr);
return df.format(num);
}
public static void main(String[] arg){
StringManager sm = new StringManager();
//sm.getDaysFromString("1年3个月20日");
String a = sm.fillzero(10L, 2);
System.out.println(a);
}
}
JAVA字符串的一些特殊应用——数字变成字符串并位数补足0等
最新推荐文章于 2022-01-18 20:10:19 发布