feat: 新增 StringTools#toQuotedString 方法

This commit is contained in:
zhouxy108 2025-05-18 15:18:52 +08:00
parent 3ca2ec3be0
commit f9b4c3c58c
2 changed files with 49 additions and 0 deletions

View File

@ -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");
}

View File

@ -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();