Real World Example

Chat and Payment Text Formatting

Messaging and payment apps format a lot of text: WhatsApp shows a shortened preview of the last message in the chat list, and payment apps mask phone numbers and account numbers before showing them.

Example

Preview, masking and a notification message with templates:

fun main() {
    val lastMessage = "Hey! Are we still meeting for lunch at the new place near the office?"
    val preview = if (lastMessage.length > 30) lastMessage.take(30) + "..." else lastMessage
    println("Chat preview: $preview")

    val phone = "9876543210"
    val masked = phone.take(2) + "*".repeat(6) + phone.takeLast(2)
    println("OTP sent to +91 $masked")

    val account = "123456789012"
    println("A/c XX${account.takeLast(4)} debited")

    val sender = "amma"
    val unread = 3
    println("${sender.replaceFirstChar { it.uppercase() }} sent you $unread new message${if (unread > 1) "s" else ""}")
}

Output

Chat preview: Hey! Are we still meeting for ...
OTP sent to +91 98******10
A/c XX9012 debited
Amma sent you 3 new messages

Practice

Exercise: Given val email = " [email protected] ", print the cleaned email in lowercase without spaces, and then the user name part before @.

Show answer
fun main() {
    val email = "  [email protected]  "
    val clean = email.trim().lowercase()
    println(clean)                       // [email protected]
    println(clean.substringBefore("@"))  // rahul.verma
}