JAVA字符串的一些特殊应用——数字变成字符串并位数补足0等

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值