From 716cda893dbe115b5b6aa9d783e7fa23a9d5ce87 Mon Sep 17 00:00:00 2001 From: ZhouXY108 Date: Sat, 27 May 2023 04:09:11 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=AD=97=E7=AC=A6=E4=B8=B2?= =?UTF-8?q?=E2=80=9C=E8=A1=A5=E4=BD=8D=E2=80=9D=E6=96=B9=E6=B3=95=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../zhouxy/plusone/commons/util/StrUtil.java | 34 +++++++++++++++++++ .../plusone/commons/util/StrUtilTests.java | 23 +++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 src/main/java/xyz/zhouxy/plusone/commons/util/StrUtil.java create mode 100644 src/test/java/xyz/zhouxy/plusone/commons/util/StrUtilTests.java diff --git a/src/main/java/xyz/zhouxy/plusone/commons/util/StrUtil.java b/src/main/java/xyz/zhouxy/plusone/commons/util/StrUtil.java new file mode 100644 index 0000000..ca45407 --- /dev/null +++ b/src/main/java/xyz/zhouxy/plusone/commons/util/StrUtil.java @@ -0,0 +1,34 @@ +package xyz.zhouxy.plusone.commons.util; + +import java.util.Arrays; + +public class StrUtil { + + public static String fillBefore(String src, int minLength, char c) { + if (src.length() >= minLength) { + return src; + } + char[] result = new char[minLength]; + Arrays.fill(result, c); + for (int i = 1; i <= src.length(); i++) { + result[minLength - i] = src.charAt(src.length() - i); + } + return String.valueOf(result); + } + + public static String fillAfter(String src, int length, char c) { + if (src.length() >= length) { + return src; + } + char[] result = new char[length]; + Arrays.fill(result, c); + for (int i = 0; i < src.length(); i++) { + result[i] = src.charAt(i); + } + return String.valueOf(result); + } + + private StrUtil() { + throw new IllegalStateException("Utility class"); + } +} diff --git a/src/test/java/xyz/zhouxy/plusone/commons/util/StrUtilTests.java b/src/test/java/xyz/zhouxy/plusone/commons/util/StrUtilTests.java new file mode 100644 index 0000000..7ced2dc --- /dev/null +++ b/src/test/java/xyz/zhouxy/plusone/commons/util/StrUtilTests.java @@ -0,0 +1,23 @@ +package xyz.zhouxy.plusone.commons.util; + +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +class StrUtilTests { + + private static final Logger log = LoggerFactory.getLogger(StrUtilTests.class); + + @Test + void testFillZero() { + char c = '='; + log.info(StrUtil.fillBefore("1234", 6, c)); + log.info(StrUtil.fillBefore("12345", 6, c)); + log.info(StrUtil.fillBefore("123456", 6, c)); + log.info(StrUtil.fillBefore("1234567", 6, c)); + log.info(StrUtil.fillAfter("1234", 6, c)); + log.info(StrUtil.fillAfter("12345", 6, c)); + log.info(StrUtil.fillAfter("123456", 6, c)); + log.info(StrUtil.fillAfter("1234567", 6, c)); + } +}