Shiraji's Blog

Visualize Kotlin substringXxx Methods

I found very hard time to memorize the following methods.

  • substringAfter
  • substringAfterLast
  • substringBefore
  • substringBeforeLast

Here is the visuals that illustrate the differences between these methods.

substringAfter

substringAfter tries to find the character(s) from “beginning”, and substrings “after” the characters

substringAfter

substringAfterLast

substringAfterLast tries to find the character(s) from “last”, and substrings “after” the characters

substringAfterLast

substringBefore

substringBefore tries to find the character(s) from “beginning”, and substrings “before” the characters

substringBefore

substringBeforeLast

substringBeforeLast tries to find the character(s) from “last”, and substrings “before” the characters

substringBeforeLast

Text Summary

The following list is the summary of these methods.

  • “Last” -> find a match from the end
  • no “Last” -> find a match from the beginning
  • “Before” -> get all text before the match
  • “After” -> get all text after the match
  • The substring result does not include the matched text