已有格式进行数据提炼格式化输出

Format2Format

因为要转换一个已有格式的字符串又没找到已有的类于是写了
一个很简单的工具类。特此留存!欢迎使用欢迎优化。

直接贴代码:
public class Format2Format {
   static final String NEED_CHAR = "~";

   private static boolean isEmpty(String str) {
       return str == null || str.length() == 0;
   }

   private static boolean needStrEquals(String format, String toFormat) {
       int formatNeedSize = needStrSize(format);
       int toFormatNeedSize = needStrSize(toFormat);
       return formatNeedSize > 0 && toFormatNeedSize > 0 && formatNeedSize >= toFormatNeedSize;
   }

   private static int needStrSize(String format) {
       int size = 0;
       for (int x = 0; x < format.length(); x++) {
           String tmp = String.valueOf(format.charAt(x));
           if (NEED_CHAR.equals(tmp)) {
               size++;
           }
       }
       return size;
   }

   private static ArrayList<String> getNeedArr(String src, String format) {
       ArrayList<String> needArr = new ArrayList();
       for (int x = 0; x < format.length(); x++) {
           String tmp = String.valueOf(format.charAt(x));
           if (NEED_CHAR.equals(tmp)) {
               needArr.add(src.substring(x, x + 1));
           }
       }
       return needArr;
   }

   /**
    * 格式化输出
    *
    * @param src
    * @param format
    * @param toFormat
    * @return
    */
   public static String format(String src, String format, String toFormat) {
       if (isEmpty(src) || isEmpty(format) || isEmpty(toFormat) || src.length() != format.length() || !needStrEquals(format, toFormat)) {
           return null;
       }
       StringBuffer out = new StringBuffer();
       ArrayList<String> needArr = getNeedArr(src, format);
       int need = 0;
       for (int x = 0; x < toFormat.length(); x++) {
           String tmp = String.valueOf(toFormat.charAt(x));
           if (NEED_CHAR.equals(tmp)) {
               out.append(needArr.get(need));
               need++;
           } else {
               out.append(tmp);
           }
       }
       return out.toString();
   } 
}
这个类可以干啥

如将
2020年08月31日周二 12时12分
转成
202008311212
只需要

Format2Format.format("2020年08月31日周二 12时12分", "~~~~年~~月~~日周二 ~~时~~分", "~~~~~~~~~~")

需要转成
@2@0@2@0@08@3@1@1@2@1@2@

Format2Format.format("2020年08月31日周二 12时12分", "~~~~年~~月~~日周二 ~~时~~分", "@~@~@~@~@~@~@~@~@~@~")

需要201908

Format2Format.format("2020年08月31日周二 12时12分", "~~~~年~~月~~日周二 ~~时~~分", "~~1~~~")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值