Strings are interesting, and they are similar to Python operations. The reference for this article is Kotlin from The Basics to the Field.

Simple manipulation of 1_ strings

1.1 _ to find

  • str.first()
  • str.last()
  • str.get(index)
var str = "Hello World"
str.first()
str.last()
str.get(3)
str[3]
str.indexOf('o')
// Find the first occurrence of the string in the original string
str.lastIndexOf('o')
// Find the last occurrence of the string in the original string
Copy the code

1.2 _ interception

  • STR. The substring (3, 7)
  • STR. The substring (IntRange (3, 7))
  • STR. SubSequence (3, 7)
  • STR. SubSequence (IntRange (3, 7))

1.3 _ instead

  • str.replace(old,new,ignoreCase=false)

  • str.replaceFirst(old,new)

  • Str.replacebefore (target,new) replaces all strings before the first string that satisfies the condition with new

  • Str.replaceafter (target,new) replaces all strings after the first string that satisfies the condition with new

var str = "Hello World! Hello World!"
str.replaceBefore("!"."Kotlin")
// "Kotlin! Hello World!"
str.replaceAfter("Hello "."Kotlin")
// "Hello Kotlin!"
Copy the code

1.4 _ separated

  • str.split()
val str = "Hello.Kotlin/world"
var spl = str.split("."."/")
// [hello,kotlin,world]
Copy the code

1.5 _ to space

  • str.trim() Go to the space in front
  • str.trimEnd()Go to the space behind
var str = " Hello World "
str.trim()  // "Hello World "
str.trimEnd()  // " Hello World"
Copy the code

2_ Template expression

String template expressions are composed of ${variable name/function/expression} and can also omit {}, such as $variable name.

var a = 1
var s1 = "a is $a"
var s2 = "a is ${a}"

var str = "a is 1"
var str1 = "${s2.replace("is"."was")}"

var str2 = "${$}8.88"
Copy the code