KOTLIN / CHAPTER 03

Text transformations and search boundaries

Intermediate

Normalize text while preserving the intended meaning of positions.

By the end of this chapter

  • Separate strings from mutable builders
  • Handle absent search results
  • State text-index assumptions

The idea

Kotlin String values are immutable, so operations such as trim and substring return values rather than changing the original binding’s text. A StringBuilder is appropriate when many fragments need controlled accumulation. Search functions such as indexOf use a sentinel when no match exists; check that result before using it as a slicing boundary. A failed search is not a valid position.

On the JVM, string indices refer to UTF-16 code units rather than necessarily complete displayed characters. Simple ASCII exercises should state that restriction when they manipulate individual positions. Normalization is also a policy: trimming removes surrounding whitespace, while lowercasing changes case and may affect user-visible spelling. Keep the normalized comparison key separate from the original display value when both responsibilities matter.

Kotlin example
fun main(){ val raw="  key:value  "; val text=raw.trim(); val split=text.indexOf(':'); println(text.substring(0,split)); println(raw.length > text.length) }
Result
key
true

The normalized copy is searched and sliced; the original string still includes its surrounding spaces.

Try it yourself

Return the text before the first colon, or null when no colon exists.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

What is printed?
val s="ab:cd:ef"
println(s.substring(0,s.indexOf(':')))