mirror of
https://gitee.com/dromara/hutool.git
synced 2025-06-28 13:34:09 +08:00
fix: 修改flexibleConcat方法
This commit is contained in:
parent
1776471134
commit
33d669e94e
@ -383,8 +383,14 @@ public class StrUtil extends CharSequenceUtil implements StrPool {
|
||||
* @return flexibleConcat
|
||||
*/
|
||||
public static String flexibleConcat(String str, String left, String right, String middle, int middlePos) {
|
||||
// 预计算最终字符串的长度,避免 StringBuilder 反复扩容
|
||||
int estimatedLength = (str != null ? str.length() : 0) +
|
||||
(left != null ? left.length() : 0) +
|
||||
(right != null ? right.length() : 0) +
|
||||
(middle != null ? middle.length() : 0);
|
||||
|
||||
// 使用 StringBuilder 来提高拼接性能
|
||||
StringBuilder sb = new StringBuilder();
|
||||
StringBuilder sb = new StringBuilder(estimatedLength);
|
||||
|
||||
// 如果原始字符串不为 null,添加到 StringBuilder
|
||||
if (str != null) {
|
||||
@ -394,18 +400,21 @@ public class StrUtil extends CharSequenceUtil implements StrPool {
|
||||
// 左边拼接字符串(如果有
|
||||
Optional.ofNullable(left)
|
||||
.filter(s -> !s.isEmpty())
|
||||
.ifPresent(l -> sb.insert(0, l.toCharArray()));
|
||||
.ifPresent(l -> sb.insert(0, l));
|
||||
|
||||
// 右边拼接字符串(如果有)
|
||||
Optional.ofNullable(right)
|
||||
.filter(s -> !s.isEmpty())
|
||||
.ifPresent(sb::append);
|
||||
|
||||
// 计算 middle 的插入位置
|
||||
int adjustedMiddlePos = (left != null ? left.length() : 0) + middlePos;
|
||||
|
||||
// 中间拼接字符串(如果有且位置有效)
|
||||
Optional.ofNullable(middle)
|
||||
.filter(s -> !s.isEmpty())
|
||||
.filter(s -> middlePos >= 0 && middlePos <= sb.length())
|
||||
.ifPresent(m -> sb.insert(middlePos, m.toCharArray()));
|
||||
.filter(s -> adjustedMiddlePos >= 0 && adjustedMiddlePos <= sb.length())
|
||||
.ifPresent(m -> sb.insert(adjustedMiddlePos, m));
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
@ -641,4 +641,20 @@ public class StrUtilTest {
|
||||
final String s = StrUtil.indexedFormat("a{0,number,#}", 1234567);
|
||||
Assertions.assertEquals("a1234567", s);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void flexibleConcat() {
|
||||
/**
|
||||
* 往左边填充
|
||||
*/
|
||||
System.out.println(StrUtil.flexibleConcat("hello", ">>>", null, null, -1));
|
||||
/**
|
||||
* 往右边填充
|
||||
*/
|
||||
System.out.println(StrUtil.flexibleConcat("java", null, "!", null, -1));
|
||||
/**
|
||||
* 往左右中间填充
|
||||
*/
|
||||
System.out.println(StrUtil.flexibleConcat("world", "abc", "xyz", "123", 3));
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user