diff --git a/plusone-commons/src/main/java/xyz/zhouxy/plusone/commons/util/StringTools.java b/plusone-commons/src/main/java/xyz/zhouxy/plusone/commons/util/StringTools.java index 821d219..cf1aec7 100644 --- a/plusone-commons/src/main/java/xyz/zhouxy/plusone/commons/util/StringTools.java +++ b/plusone-commons/src/main/java/xyz/zhouxy/plusone/commons/util/StringTools.java @@ -220,6 +220,23 @@ public class StringTools { return String.valueOf(charArray); } + /** + * 转换为带引号的字符串 + * + * @param value 值 + * @return 带引号的字符串 + * @since 1.1.0 + */ + public static String toQuotedString(@Nullable String value) { + if (value == null) { + return "null"; + } + if (value.isEmpty()) { + return "\"\""; + } + return "\"" + value + "\""; + } + private StringTools() { throw new IllegalStateException("Utility class"); } diff --git a/plusone-commons/src/test/java/xyz/zhouxy/plusone/commons/util/StringToolsTests.java b/plusone-commons/src/test/java/xyz/zhouxy/plusone/commons/util/StringToolsTests.java index 1d43950..dd82523 100644 --- a/plusone-commons/src/test/java/xyz/zhouxy/plusone/commons/util/StringToolsTests.java +++ b/plusone-commons/src/test/java/xyz/zhouxy/plusone/commons/util/StringToolsTests.java @@ -370,6 +370,38 @@ class StringToolsTests { // #endregion - desensitize // ================================ + // ================================ + // #region - toQuotedString + // ================================ + + @Test + void toQuotedString_NullInput_ReturnsNullStr() { + String result = StringTools.toQuotedString(null); + assertEquals("null", result); + + assertEquals("The value is null.", String.format("The value is %s.", result)); + } + + @Test + void toQuotedString_EmptyString_ReturnsEmptyString() { + String result = StringTools.toQuotedString(""); + assertEquals("\"\"", result); + + assertEquals("The value is \"\".", String.format("The value is %s.", result)); + } + + @Test + void toQuotedString_ValidInput_ReturnsQuotedString() { + String result = StringTools.toQuotedString("Hello World"); + assertEquals("\"Hello World\"", result); + + assertEquals("The value is \"Hello World\".", String.format("The value is %s.", result)); + } + + // ================================ + // #endregion - toQuotedString + // ================================ + @Test void test_constructor_isNotAccessible_ThrowsIllegalStateException() { Constructor[] constructors = StringTools.class.getDeclaredConstructors();