Snippets: Java: String

 20th August 2020 at 2:19pm

Multi-line String

Java(至今 JDK 11)没有多行字符串的 literal。你可以复制一个多行字符串,再在 IntelliJ 里面的 "" 中粘贴,IDE 会自动帮你生成多行字符串。

如果要手写多行字符串,可以参考这个 SO 回答

Format String

Java 的字符串格式化。

用比较新的 MessageFormat.format() 或者 C 风格的 String.format()

MessageFormat.format("String is \"{1}\", number is {0}.", 42, "foobar");
String.format("%s %d", "hello", 1);

// Output: String is "foobar", number is 42

老的方式 String.format

String.format("Hello %s, %d", "world", 42);

Simple Template Substitute

org.apache.commons.text 包提供了一个简单的方法:

Map valuesMap = HashMap();
valuesMap.put("animal", "quick brown fox");
valuesMap.put("target", "lazy dog");
String templateString = "The ${animal} jumped over the ${target}.";
StrSubstitutor sub = new StrSubstitutor(valuesMap);
String resolvedString = sub.replace(templateString);

Join

Join and Split Arrays and Collections in Java:

@Test
public void whenConvertArrayToString_thenConverted() {
    String[] animals = new String[] { "Dog", "Cat", "Bird", "Cow" };
    String result = Arrays.stream(animals).collect(Collectors.joining(", "));
 
    assertEquals(result, "Dog, Cat, Bird, Cow");
}