目录
六、通过特定拼接字符拼接字符串, 如 ["1", "2"], 拼接字符 "_", 则拼接结果为 1_2,如果待拼接的字符为单个字符,则直接返回该字符
九、对内容超长的标题进行截取 -> 特定长度字符串 + "..."
字符转换工具类是一种常用的工具类,它可以将不同格式的字符转换成另一种格式,方便开发人员在不同的场合使用。这些字符可能包括数字、字母、日期等等,转换的格式也有很多种,比如十六进制、二进制、日期格式化等等。在实际开发中,我们经常需要进行字符转换,因此了解和掌握字符转换工具类是非常重要的。
以下提供的字符转换方法、都是日常使用的一些方法!
一、将 byte[] 转为十六进制 String
/**
* 将 byte[] 转为十六进制 String
*
* @param message byte[],待转换的字节数组
* @return String
*/
public static String convertByteArrayToHexString(byte[] message) {
if (null == message || message.length == 0) {
LOGGER.error("error message: 待转换的数组信息为空,请检查!");
return "";
}
StringBuilder stringBuilder = new StringBuilder();
for (byte b : message) {
int temp = b & 0xFF;
String tempResult = Integer.toHexString(temp);
if (tempResult.length() < 2) {
stringBuilder.append("0").append(tempResult);
} else {
stringBuilder.append(tempResult);
}
}
return stringBuilder.toString();
}
二、将十六进制 String 转为 byte[]
/**
* 将十六进制 String 转为 byte[]
*
* @param message String,待转换的十六进制字符串
* @return byte[]
*/
public static byte[] convertHexStringToByteArray(String message) {
if (StringUtil.isEmpty(message)) {
LOGGER.error("error message: 待转换的十六进制字符串信息为空,请检查!");
return new byte[0];
}
byte[] result = new byte[message.length() / 2];
for (int i = 0; i < result.length; i++) {
String temp = message.substring(2 * i, 2 * i + 2);
result[i] = ((byte) Integer.parseInt(temp, 16));
}
return result;
}
三、指定编码格式将 String 转为 byte[]
Charset、是指编码格式
如:StandardCharsets.UTF_8、或其他类型的编码格式、等等
/**
* 指定编码格式将 String 转为 byte[]
*
* @param message String,待转换的字符串
* @param encoding String,编码格式
* @return byte[]
*/
public static byte[] convertStringToByteArrayWithEncoding(String message, Charset encoding) {
if (StringUtil.isEmpty(message)) {
LOGGER.error("error message: 待转换的字符串信息为空或者编码格式无效,请检查!");
return new byte[0];
}
return message.getBytes(encoding);
}
四、指定编码格式将 byte[] 转为 String
/**
* 指定编码格式将 byte[] 转为 String
*
* @param message byte[],待转换的字节数组
* @param encoding String,编码格式
* @return String
*/
public static String convertByteArrayToStringWithEncoding(byte[] message, Charset encoding) {
if (null == message || message.length == 0) {
LOGGER.error("error message: 待转换的数组信息为空或者编码格式无效,请检查!");
return "";
}
return new String(message, encoding);
}
五、将字符串中的所有字母转换为大写
/**
* 将字符串中的所有字母转换为大写
* @param str 需要转换的字符串
* @return 转换后的字符串
*/
public static String toUpperCase(String str) {
if (str == null) {
return null;
}
return str.toUpperCase();
}
六、通过特定拼接字符拼接字符串, 如 ["1", "2"], 拼接字符 "_", 则拼接结果为 1_2,如果待拼接的字符为单个字符,则直接返回该字符
/**
* 通过特定拼接字符拼接字符串, 如 ["1", "2"], 拼接字符 "_", 则拼接结果为 1_2,如果待拼接的字符为单个字符,则直接返回该字符
*
* @param strList List<String>
* @param contactCharacter String
* @return String
*/
public static String genStringWithSpecialCondition(List<String> strList, String contactCharacter) {
if (CollectionUtil.isEmpty(strList) || null == contactCharacter) {
LOGGER.error("error message: 待生成 String 形式值的参数无效,请重新输入!");
return ConstantUtil.SPECIAL_CHARACTER_EMPTY;
}
if (strList.size() == 1) {
LOGGER.info("tip message: 待拼接的字符只有一个,直接返回该字符!");
return strList.get(0);
}
StringBuilder stringBuilder = new StringBuilder();
for (String item : strList) {
if (null != item && item.length() > 0) {
stringBuilder.append(item).append(contactCharacter);
}
}
if (stringBuilder.length() > 0) {
stringBuilder.deleteCharAt(stringBuilder.length() - 1);
}
return stringBuilder.toString();
}
七、分割字符串
/**
* 分割字符串
*
* @param str String 待分割的字符串
* @param start 开始位置
* @param end 结束位置
* @return String
*/
public static String subString(String str, int start, int end) {
if (isEmpty(str) || start < 0 || end <= 0 || start >= end) {
return str;
}
if (end > str.length()) {
end = str.length();
}
return str.substring(start, end);
}
/**
* 分割字符串
*
* @param str String 待分割的字符串
* @param start 开始位置
* @return String
*/
public static String subString(String str, int start) {
if (isEmpty(str) || start < 0 || start >= str.length()) {
return str;
}
return subString(str, start, str.length());
}
八、去除字符传两端的空白字符
静态常量:
1、public static final String DEFAULT_STRING_CHECK_MODE = "^\\s+|\\s+$|^\\p{Zs}+|\\p{Zs}+$";
2、public static final String SPECIAL_CHARACTER_EMPTY = "";
/**
* 去除字符传两端的空白字符
*
* @param s String
* @return String
*/
public static String trim(String s) {
return isEmpty(s) ? s : s.replaceAll(ConstantUtil.DEFAULT_STRING_CHECK_MODE, ConstantUtil.SPECIAL_CHARACTER_EMPTY);
}
九、对内容超长的标题进行截取 -> 特定长度字符串 + "..."
静态常量:
1、public static final int DEFAULT_TITLE_OVERLONG = 36;
2、public static final String SPECIAL_CHARACTER_CONTACT = "...";
/**
* 对内容超长的标题进行截取 -> 特定长度字符串 + "..."
*
* @param newsTitle String 待检测并截取的标题
* @return String
*/
public static String subNewsTitleWithFixedLength(String newsTitle) {
if (StringUtil.isEmpty(newsTitle)) {
return ConstantUtil.SPECIAL_CHARACTER_EMPTY;
}
// 处理标题过长的场景
if (newsTitle.length() > ConstantUtil.DEFAULT_TITLE_OVERLONG) {
return newsTitle.substring(0, ConstantUtil.DEFAULT_TITLE_OVERLONG).concat(ConstantUtil.SPECIAL_CHARACTER_CONTACT);
}
return newsTitle;
}
十、字符串大小写转换
枚举值:stringConvertType 枚举代码如下
public enum StringConvertType implements EnumInterface {
// 1-小写转换
STRING_CONVERT_TYPE_LOWER("1", "小写转换"),
// 2-大写转换
STRING_CONVERT_TYPE_UPPER("2", "大写转换");
final String value;
final String label;
StringConvertType(String value, String label) {
this.value = value;
this.label = label;
}
public static StringConvertType getEnumByValue(String value) {
for (StringConvertType stringConvertType : StringConvertType.values()) {
if (stringConvertType.value.equals(value)) {
return stringConvertType;
}
}
return null;
}
@Override
public String getValue() {
return this.value;
}
@Override
public String getLabel() {
return this.label;
}
}
10.1、大小写转换代码如下:
/**
* 字符串大小写转换
*
* @param str String 原始字串信息
* @param stringConvertType SystemEnumEntity.StringConvertType 大小写转换类型
* @return String
*/
public static String stringUpperOrLowerConvert(String str, SystemEnumEntity.StringConvertType stringConvertType) {
if (isEmpty(str)) {
return str;
}
switch (stringConvertType) {
case STRING_CONVERT_TYPE_LOWER:
return str.toLowerCase(Locale.CHINA);
case STRING_CONVERT_TYPE_UPPER:
return str.toUpperCase(Locale.CHINA);
default:
LOGGER.error("error message: 暂不支持的大小写转换类型 <{}>", stringConvertType.getLabel());
return str;
}
}
十一、 去除字符串中的非数字
静态常量:
public static final String DEFAULT_REGEX_FILTER_NON_NUMBER = "\\D";
public static final String SPECIAL_CHARACTER_EMPTY = "";
/**
* 去除字符串中的非数字
*
* @param str String
* @return String
*/
public static String filterNonNumber(String str) {
if (isEmpty(str)) {
return str;
}
return str.replaceAll(ConstantUtil.DEFAULT_REGEX_FILTER_NON_NUMBER, ConstantUtil.SPECIAL_CHARACTER_EMPTY);
}
十二、过滤首 头部 或 尾部 的特殊字符
/**
* 过滤首 头部 或 尾部 的特殊字符
* 注意该方法是循环去除,直至没有符合过滤条件的数据
* 暂不过滤字符中间出现的特殊字符,如有需要,后续扩展
*
* @param initialStr String 待处理的字符
* @param searchStr String 需过滤的特殊字符
* @param headFlag boolean True-头部过滤 False-尾部过滤
* @return String
*/
public static String filterSpecialCharacter(String initialStr, String searchStr, boolean headFlag) {
if (StringUtil.isEmpty(initialStr) || StringUtil.isEmpty(searchStr)) {
return initialStr;
}
// 过滤头部特殊字符
if (headFlag) {
int hitIndex = initialStr.indexOf(searchStr);
if (hitIndex == -1 || hitIndex > 0) {
return initialStr;
}
initialStr = initialStr.substring(hitIndex + searchStr.length());
return filterSpecialCharacter(initialStr, searchStr, true);
}
// 过滤末尾特殊字符
else {
int hitIndex = initialStr.lastIndexOf(searchStr);
if (hitIndex == -1 || hitIndex < initialStr.length() - 1) {
return initialStr;
}
initialStr = initialStr.substring(0, hitIndex);
return filterSpecialCharacter(initialStr, searchStr, false);
}
}
十三、去除头部特殊字符
静态常量:
public static final List<String> DEFAULT_SPECIAL_FILTER_CHARACTER_LIST = List.of(".", "/", "\\", ":", ";", "?", "#", ",");
/**
* 去除头部特殊字符
*
* @param initialStr String 原始字符
* @return String
*/
public static String filterHeadSpecialCharacter(String initialStr) {
// 去除 头部 . / \ 的数据
for (String str : ConstantUtil.DEFAULT_SPECIAL_FILTER_CHARACTER_LIST) {
initialStr = filterSpecialCharacter(initialStr, str, true);
}
return initialStr;
}
十四、去除尾部特殊字符
静态常量同 十三 使用的一样
/**
* 去除尾部特殊字符
*
* @param initialStr String 原始字符
* @return String
*/
public static String filterTailSpecialCharacter(String initialStr) {
// 去除 尾部 . / \ 的数据
for (String str : ConstantUtil.DEFAULT_SPECIAL_FILTER_CHARACTER_LIST) {
initialStr = filterSpecialCharacter(initialStr, str, false);
}
return initialStr;
}
十五、忽略 null 或 空字符串的字符拼接
/**
* 忽略 null 或 空字符串的字符拼接
*
* @param delimiter String 分割符
* @param str String... 可变数量的字符参数
* @return String
*/
public static String joinIgnoreEmpty(String delimiter,
String... str) {
if (CollectionUtil.isEmpty(str)) {
return ConstantUtil.SPECIAL_CHARACTER_EMPTY;
}
delimiter = Optional.ofNullable(delimiter).orElse(ConstantUtil.SPECIAL_CHARACTER_EMPTY);
return Stream.of(str)
.filter(StringUtil::isNotEmpty)
.collect(Collectors.joining(delimiter));
}
以上就是一些常用的字符串转换工具了。
多多看书、好好学习。