Java 与 Kotlin 中的字符串

This guide contains examples of how to perform typical tasks with strings in Java and Kotlin. It will help you migrate from Java to Kotlin and write your code in the authentically Kotlin way.

字符串连接

In Java, you can do this in the following way:

  1. // Java
  2. String name = "Joe";
  3. System.out.println("Hello, " + name);
  4. System.out.println("Your name is " + name.length() + " characters long");

In Kotlin, use the dollar sign ($) before the variable name to interpolate the value of this variable into your string:

  1. fun main() {
  2. //sampleStart
  3. // Kotlin
  4. val name = "Joe"
  5. println("Hello, $name")
  6. println("Your name is ${name.length} characters long")
  7. //sampleEnd
  8. }

You can interpolate the value of a complicated expression by surrounding it with curly braces, like in ${name.length}. See string templates for more information.

构建字符串

In Java, you can use the StringBuilder:

  1. // Java
  2. StringBuilder countDown = new StringBuilder();
  3. for (int i = 5; i > 0; i--) {
  4. countDown.append(i);
  5. countDown.append("\n");
  6. }
  7. System.out.println(countDown);

In Kotlin, use buildString() – an inline function that takes logic to construct a string as a lambda argument:

  1. fun main() {
  2. //sampleStart
  3. // Kotlin
  4. val countDown = buildString {
  5. for (i in 5 downTo 1) {
  6. append(i)
  7. appendLine()
  8. }
  9. }
  10. println(countDown)
  11. //sampleEnd
  12. }

Under the hood, the buildString uses the same StringBuilder class as in Java, and you access it via an implicit this inside the lambda.

Learn more about lambda coding conventions.

由集合内元素创建字符串

In Java, you use the Stream API to filter, map, and then collect the items:

  1. // Java
  2. List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6);
  3. String invertedOddNumbers = numbers
  4. .stream()
  5. .filter(it -> it % 2 != 0)
  6. .map(it -> -it)
  7. .map(Object::toString)
  8. .collect(Collectors.joining("; "));
  9. System.out.println(invertedOddNumbers);

In Kotlin, use the joinToString() function, which Kotlin defines for every List:

  1. fun main() {
  2. //sampleStart
  3. // Kotlin
  4. val numbers = listOf(1, 2, 3, 4, 5, 6)
  5. val invertedOddNumbers = numbers
  6. .filter { it % 2 != 0 }
  7. .joinToString(separator = ";") {"${-it}"}
  8. println(invertedOddNumbers)
  9. //sampleEnd
  10. }

In Java, if you want spaces between your delimiters and following items, you need to add a space to the delimiter explicitly.

字符串 - 图1

Learn more about joinToString() usage.

如果字符串为空白就设置默认值

In Java, you can use the ternary operator:

  1. // Java
  2. public void defaultValueIfStringIsBlank() {
  3. String nameValue = getName();
  4. String name = nameValue.isBlank() ? "John Doe" : nameValue;
  5. System.out.println(name);
  6. }
  7. public String getName() {
  8. Random rand = new Random();
  9. return rand.nextBoolean() ? "" : "David";
  10. }

Kotlin provides the inline function ifBlank() that accepts the default value as an argument:

  1. // Kotlin
  2. import kotlin.random.Random
  3. //sampleStart
  4. fun main() {
  5. val name = getName().ifBlank { "John Doe" }
  6. println(name)
  7. }
  8. fun getName(): String =
  9. if (Random.nextBoolean()) "" else "David"
  10. //sampleEnd

替换字符串首尾处的(多个)字符

In Java, you can use the replaceAll()) function. The replaceAll() function in this case accepts regular expressions ^## and ##$, which define strings starting and ending with ## respectively:

  1. // Java
  2. String input = "##place##holder##";
  3. String result = input.replaceAll("^##|##$", "");
  4. System.out.println(result);

In Kotlin, use the removeSurrounding() function with the string delimiter ##:

  1. fun main() {
  2. //sampleStart
  3. // Kotlin
  4. val input = "##place##holder##"
  5. val result = input.removeSurrounding("##")
  6. println(result)
  7. //sampleEnd
  8. }

正则替换

In Java, you can use the Pattern and the Matcher classes, for example, to obfuscate some data:

  1. // Java
  2. String input = "login: Pokemon5, password: 1q2w3e4r5t";
  3. Pattern pattern = Pattern.compile("\\w*\\d+\\w*");
  4. Matcher matcher = pattern.matcher(input);
  5. String replacementResult = matcher.replaceAll(it -> "xxx");
  6. System.out.println("Initial input: '" + input + "'");
  7. System.out.println("Anonymized input: '" + replacementResult + "'");

In Kotlin, you use the Regex class that simplifies working with regular expressions. Additionally, use raw strings to simplify a regex pattern by reducing the count of backslashes:

  1. fun main() {
  2. //sampleStart
  3. // Kotlin
  4. val regex = Regex("""\w*\d+\w*""") // multiline string
  5. val input = "login: Pokemon5, password: 1q2w3e4r5t"
  6. val replacementResult = regex.replace(input, replacement = "xxx")
  7. println("Initial input: '$input'")
  8. println("Anonymized input: '$replacementResult'")
  9. //sampleEnd
  10. }

字符串拆分

In Java, to split a string with the period character (.), you need to use shielding (\\). This happens because the split()) function of the String class accepts a regular expression as an argument:

  1. // Java
  2. System.out.println(Arrays.toString("Sometimes.text.should.be.split".split("\\.")));

In Kotlin, use the Kotlin function split(), which accepts varargs of delimiters as input parameters:

  1. fun main() {
  2. //sampleStart
  3. // Kotlin
  4. println("Sometimes.text.should.be.split".split("."))
  5. //sampleEnd
  6. }

If you need to split with a regular expression, use the overloaded split() version that accepts the Regex as a parameter.

取子串

In Java, you can use the substring()) function, which accepts an inclusive beginning index of a character to start taking the substring from. To take a substring after this character, you need to increment the index:

  1. // Java
  2. String input = "What is the answer to the Ultimate Question of Life, the Universe, and Everything? 42";
  3. String answer = input.substring(input.indexOf("?") + 1);
  4. System.out.println(answer);

In Kotlin, you use the substringAfter() function and don’t need to calculate the index of the character you want to take a substring after:

  1. fun main() {
  2. //sampleStart
  3. // Kotlin
  4. val input = "What is the answer to the Ultimate Question of Life, the Universe, and Everything? 42"
  5. val answer = input.substringAfter("?")
  6. println(answer)
  7. //sampleEnd
  8. }

Additionally, you can take a substring after the last occurrence of a character:

  1. fun main() {
  2. //sampleStart
  3. // Kotlin
  4. val input = "To be, or not to be, that is the question."
  5. val question = input.substringAfterLast(",")
  6. println(question)
  7. //sampleEnd
  8. }

使用多行字符串

Before Java 15, there were several ways to create a multiline string. For example, using the join()) function of the String class:

  1. // Java
  2. String lineSeparator = System.getProperty("line.separator");
  3. String result = String.join(lineSeparator,
  4. "Kotlin",
  5. "Java");
  6. System.out.println(result);

In Java 15, text blocks appeared. There is one thing to keep in mind: if you print a multiline string and the triple-quote is on the next line, there will be an extra empty line:

  1. // Java
  2. String result = """
  3. Kotlin
  4. Java
  5. """;
  6. System.out.println(result);

The output: Java 15 multiline output

If you put the triple-quote on the same line as the last word, this difference in behavior disappears.

In Kotlin, you can format your line with the quotes on the new line, and there will be no extra empty line in the output. The left-most character of any line identifies the beginning of the line. The difference with Java is that Java automatically trims indents, and in Kotlin you should do it explicitly:

  1. fun main() {
  2. //sampleStart
  3. // Kotlin
  4. val result = """
  5. Kotlin
  6. Java
  7. """.trimIndent()
  8. println(result)
  9. //sampleEnd
  10. }

The output: Kotlin multiline output

To have an extra empty line, you should add this empty line to your multiline string explicitly.

In Kotlin, you can also use the trimMargin() function to customize the indents:

  1. // Kotlin
  2. fun main() {
  3. val result = """
  4. # Kotlin
  5. # Java
  6. """.trimMargin("#")
  7. println(result)
  8. }

Learn more about multiline strings.

下一步做什么?

If you have a favorite idiom, we invite you to share it by sending a pull request.