Kotlin Strings

Working with text data in Kotlin

📝 What are Kotlin Strings?

Strings represent text data in Kotlin. They're sequences of characters enclosed in quotes, supporting operations like concatenation, interpolation, and various text manipulations for handling user input and messages.


// Creating strings
val greeting = "Hello, World!"
val name = "Alice"
val message = "Welcome, $name!"    // String interpolation
val multiLine = """
    This is a
    multi-line string
""".trimIndent()
                                    

Output:

greeting: Hello, World!

message: Welcome, Alice!

multiLine: This is a
multi-line string

String Features

🔤

String Literals

Create text with quotes

val text = "Hello"
🔗

Concatenation

Join strings together

val full = "Hello" + " World"
💬

Interpolation

Embed variables in strings

val msg = "Hi, $name!"
📏

String Methods

Built-in string operations

val len = text.length

🔹 Creating Strings

Different ways to create and define strings:

// Basic string creation
val simpleString = "Hello, Kotlin!"
val emptyString = ""
val singleChar = "A"

// Escape sequences
val withQuotes = "She said, \"Hello!\""
val withNewline = "Line 1\nLine 2"
val withTab = "Name:\tJohn"
val withBackslash = "Path: C:\\Users\\John"

// Raw strings (triple quotes)
val rawString = """
    This is a raw string.
    It can contain "quotes" and \backslashes
    without escaping them.
    Newlines are preserved.
""".trimIndent()

// String from other types
val number = 42
val numberString = number.toString()    // "42"
val boolString = true.toString()        // "true"

Output:

simpleString: Hello, Kotlin!

withQuotes: She said, "Hello!"

withNewline: Line 1
Line 2

numberString: "42"

🔹 String Interpolation

Embed variables and expressions directly in strings:

val firstName = "John"
val lastName = "Doe"
val age = 30
val salary = 50000.0

// Simple variable interpolation
val greeting = "Hello, $firstName!"
val fullName = "Full name: $firstName $lastName"

// Expression interpolation with curly braces
val info = "Name: ${firstName.uppercase()}, Age: $age"
val calculation = "Next year I'll be ${age + 1} years old"
val formatted = "Salary: $${String.format("%.2f", salary)}"

// Complex expressions
val status = "Status: ${if (age >= 18) "Adult" else "Minor"}"
val summary = """
    Employee Summary:
    - Name: $firstName $lastName
    - Age: $age years
    - Salary: $$salary
    - Category: ${if (salary > 40000) "High earner" else "Standard"}
""".trimIndent()

Output:

greeting: Hello, John!

info: Name: JOHN, Age: 30

calculation: Next year I'll be 31 years old

status: Status: Adult

🔹 String Operations

Common operations you can perform on strings:

val text = "  Hello, Kotlin World!  "

// Length and access
val length = text.length                    // 23
val firstChar = text[2]                     // 'H' (index 2, after spaces)
val lastChar = text[text.length - 1]       // ' ' (last space)

// Case operations
val upperCase = text.uppercase()            // "  HELLO, KOTLIN WORLD!  "
val lowerCase = text.lowercase()            // "  hello, kotlin world!  "

// Trimming whitespace
val trimmed = text.trim()                   // "Hello, Kotlin World!"
val trimStart = text.trimStart()           // "Hello, Kotlin World!  "
val trimEnd = text.trimEnd()               // "  Hello, Kotlin World!"

// Substring operations
val substring = text.substring(2, 7)        // "Hello"
val substringFrom = text.substring(8)       // "Kotlin World!  "

// Searching
val contains = text.contains("Kotlin")      // true
val startsWith = text.trim().startsWith("Hello")  // true
val endsWith = text.trim().endsWith("!")   // true
val indexOf = text.indexOf("Kotlin")       // 8

Output:

length: 23

firstChar: H

trimmed: "Hello, Kotlin World!"

contains: true

indexOf: 8

🔹 String Splitting and Joining

Break strings apart and combine them:

// Splitting strings
val csvData = "apple,banana,orange,grape"
val fruits = csvData.split(",")             // ["apple", "banana", "orange", "grape"]

val sentence = "The quick brown fox"
val words = sentence.split(" ")             // ["The", "quick", "brown", "fox"]

val email = "[email protected]"
val emailParts = email.split("@")           // ["user", "example.com"]

// Joining strings
val fruitList = listOf("apple", "banana", "orange")
val joined = fruitList.joinToString(", ")   // "apple, banana, orange"
val withAnd = fruitList.joinToString(" and ")  // "apple and banana and orange"

// Custom separators and formatting
val numbers = listOf(1, 2, 3, 4, 5)
val formatted = numbers.joinToString(
    separator = " | ",
    prefix = "[",
    postfix = "]"
)  // "[1 | 2 | 3 | 4 | 5]"

Output:

fruits: [apple, banana, orange, grape]

words: [The, quick, brown, fox]

joined: apple, banana, orange

formatted: [1 | 2 | 3 | 4 | 5]

🔹 String Replacement

Replace parts of strings with new content:

val originalText = "I love Java programming. Java is great!"

// Replace first occurrence
val replaceFirst = originalText.replaceFirst("Java", "Kotlin")
// "I love Kotlin programming. Java is great!"

// Replace all occurrences
val replaceAll = originalText.replace("Java", "Kotlin")
// "I love Kotlin programming. Kotlin is great!"

// Replace with different cases
val mixedCase = "Hello WORLD hello world"
val replaced = mixedCase.replace("hello", "hi", ignoreCase = true)
// "hi WORLD hi world"

// Remove characters
val withSpaces = "H e l l o   W o r l d"
val noSpaces = withSpaces.replace(" ", "")      // "HelloWorld"

// Replace multiple characters
val phoneNumber = "(555) 123-4567"
val cleanNumber = phoneNumber.replace(Regex("[()\\s-]"), "")  // "5551234567"

Output:

replaceFirst: I love Kotlin programming. Java is great!

replaceAll: I love Kotlin programming. Kotlin is great!

noSpaces: HelloWorld

cleanNumber: 5551234567

🧠 Test Your Knowledge

What symbol is used for string interpolation in Kotlin?