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~~~")