Skip to content

Commit

Permalink
feat(基础工具): 字符串工具类添加(判断是否为空,包含字符串)、转换文本
Browse files Browse the repository at this point in the history
  • Loading branch information
geshanzsq committed Jun 9, 2024
1 parent 6dc14d8 commit 6c9b3c5
Showing 1 changed file with 61 additions and 0 deletions.
61 changes: 61 additions & 0 deletions mogu_utils/src/main/java/com/moxi/mogublog/utils/StringUtils.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.moxi.mogublog.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collection;
Expand All @@ -24,6 +25,16 @@ public class StringUtils {
private static final Pattern CAMLE_PATTERN = Pattern.compile("_(\\w)");
private static final Pattern UNDER_LINE_PATTERN = Pattern.compile("[A-Z]");

/**
* 左括号
*/
private final static String LEFT_BRACKET = "{";

/**
* 右括号
*/
private final static String RIGHT_BRACKET = "}";

/**
* 下划线转驼峰
* @param str
Expand Down Expand Up @@ -485,6 +496,56 @@ public static Boolean isCommentSpam(String content) {
return false;
}

/**
* 判断是否为空,包含字符串
*
* @param value 值
* @return 是否为空
*/
public static boolean isNullBlank(Object value) {
return value == null
|| (value instanceof String && isBlank(String.valueOf(value)))
|| (value instanceof Collection && CollectionUtils.isEmpty((Collection) value));
}

/**
* 转换文本, {} 表示占位符,例:
* format("欢迎访问{blogName}博客,网站地址:{siteUrl}", "格姗导航", "http://gesdh.cn")
* format("欢迎访问{}博客,网站地址:{}", "格姗导航", "http://gesdh.cn")
*
* @param str 需要转换的字符串
* @param params 参数
*/
public static String format(String str, Object... params) {
if (isBlank(str) || params == null || params.length == 0) {
return str;
}
StringBuilder result = new StringBuilder();
// 数组下标
int index = 0;
while (str.contains(LEFT_BRACKET) && str.contains(RIGHT_BRACKET)) {
int start = str.indexOf(LEFT_BRACKET);
int end = str.indexOf(RIGHT_BRACKET);
// 如果 index 大于 params 数组,说明后续无需替换
if (index > (params.length - 1)) {
result.append(str);
break;
}
// 如果右 } 大于左 },直接取出 {,跳过当前,示例:欢迎访问{blogName}博客,}{网站地址:{siteUrl}
if (end < start || index > (params.length - 1)) {
result.append(str.substring(0, start + 1));
str = str.substring(start + 1);
continue;
}
result.append(str.substring(0, start));
result.append(params[index]);
str = str.substring(end + 1);
index++;
}
result.append(str);
return result.toString();
}

public static void main(String[] args) {
System.out.println(underLine(new StringBuffer("dogId")));
}
Expand Down

0 comments on commit 6c9b3c5

Please sign in to comment.