cn.zcltd.btg.sutil.StringUtil Maven / Gradle / Ivy
package cn.zcltd.btg.sutil;
public class StringUtil {
/**
* 格式化字符串为指定长度
* 若长度不够则用指定字符从指定下标补充
* 若超出指定长度,并根据是否指定截断进行截断处理
*
* @param str 待格式化字符串
* @param length 输出长度
* @param config 杂项配置,使用|分开一次排列
* replace 补位字符
* addIndex 插入下标,默认为0,即为从左侧开始插入
* isTrancate 超出长度是否截断,默认为false
* @return String
*/
public static String format2length(String str, int length, String config) {
try {
config = EmptyUtil.isNotEmpty(config) ? config : "";
String[] configs = config.split("\\|");
str = EmptyUtil.isNotEmpty(str) ? str : "";
int lengthStr = str.length();
String replaceChar = configs.length > 0 ? configs[0].trim() : " ";
replaceChar = replaceChar.length() == 0 ? " " : replaceChar;
replaceChar = replaceChar.length() > 1 ? replaceChar.substring(0, 1) : replaceChar;
String addIndexStr = configs.length > 1 ? configs[1].trim() : "0";
addIndexStr = addIndexStr.length() == 0 ? "0" : addIndexStr;
String isTrancateStr = configs.length > 2 ? configs[2].trim() : "0";
isTrancateStr = isTrancateStr.length() == 0 ? "0" : isTrancateStr;
int addIndex = Integer.parseInt(addIndexStr);
addIndex = addIndex > lengthStr ? lengthStr : addIndex;
boolean isTrancate = Boolean.parseBoolean(isTrancateStr);
int l = length - lengthStr;
if (l > 0) {
String replaceStr = "";
for (int i = 0; i < l; i++) {
replaceStr += replaceChar;
}
str = str.substring(0, addIndex) + replaceStr + str.substring(addIndex);
} else {
if (isTrancate) str = str.substring(0, length);
}
return str;
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* 格式化字符串为指定长度,若长度不够则从左侧以空格补充
*
* @param str 待格式化字符串
* @param length 输出长度
* @return String
*/
public static String format2length(String str, int length) {
return format2length(str, length, null);
}
}