Kotlin strings are fundamental data types that represent sequences of characters, and mastering Kotlin strings will significantly improve your coding efficiency.
Kotlin strings are immutable objects, meaning once you create a Kotlin string, you cannot modify its content directly. Instead, Kotlin string operations return new string objects, which is an important concept to understand when working with Kotlin strings in your applications.
Kotlin strings can be declared in multiple ways, each serving different purposes in your code. Let’s explore how you can work with Kotlin strings effectively.
The most common way to create Kotlin strings is using double quotes:
val message: String = "Hello Kotlin"
val greeting = "Welcome to Kotlin strings tutorial"
Kotlin strings support raw string literals using triple quotes, which are particularly useful for multi-line text:
val multilineString = """
This is a raw Kotlin string
It preserves line breaks
And formatting exactly as written
"""
Understanding Kotlin string properties is crucial for effective string manipulation. Let’s examine each property with practical examples.
The length
property returns the number of characters in your Kotlin string:
val text = "Kotlin Programming"
println(text.length) // Output: 17
This Kotlin string property is frequently used for validation and loop operations in real-world applications.
The indices
property provides a range of valid indices for your Kotlin string:
val language = "Kotlin"
println(language.indices) // Output: 0..5
The lastIndex
property returns the index of the last character in your Kotlin string:
val framework = "Android"
println(framework.lastIndex) // Output: 6
Kotlin strings support indexed access to individual characters, making text manipulation straightforward:
val technology = "Kotlin"
println(technology[0]) // Output: K
println(technology[technology.lastIndex]) // Output: n
You can also use the get()
function for character access in Kotlin strings:
val platform = "JetBrains"
println(platform.get(3)) // Output: B
Kotlin strings support powerful string interpolation features that make dynamic text creation elegant and readable.
val userName = "Developer"
val age = 25
val introduction = "Hi, I'm $userName and I'm $age years old"
println(introduction) // Output: Hi, I'm Developer and I'm 25 years old
For complex expressions within Kotlin strings, use curly braces:
val numbers = listOf(1, 2, 3, 4, 5)
val result = "The sum is ${numbers.sum()} and average is ${numbers.average()}"
println(result) // Output: The sum is 15 and average is 3.0
Kotlin strings come with numerous built-in functions that simplify text processing tasks.
val original = "Kotlin Programming Language"
println(original.uppercase()) // Output: KOTLIN PROGRAMMING LANGUAGE
println(original.lowercase()) // Output: kotlin programming language
println(original.capitalize()) // Output: Kotlin programming language
Kotlin strings provide various trimming functions for whitespace management:
val messyText = " Kotlin Strings Tutorial "
println(messyText.trim()) // Output: Kotlin Strings Tutorial
println(messyText.trimStart()) // Output: Kotlin Strings Tutorial
println(messyText.trimEnd()) // Output: Kotlin Strings Tutorial
Working with portions of Kotlin strings is common in data processing:
val fullText = "Learn Kotlin Programming"
println(fullText.substring(6)) // Output: Kotlin Programming
println(fullText.substring(6, 12)) // Output: Kotlin
Kotlin strings offer powerful searching capabilities:
val sentence = "Kotlin is a modern programming language"
println(sentence.contains("modern")) // Output: true
println(sentence.startsWith("Kotlin")) // Output: true
println(sentence.endsWith("language")) // Output: true
println(sentence.indexOf("programming")) // Output: 18
Comparing Kotlin strings correctly is essential for conditional logic:
val first = "Kotlin"
val second = "kotlin"
val third = "Kotlin"
println(first == third) // Output: true
println(first == second) // Output: false
println(first.equals(second, ignoreCase = true)) // Output: true
Kotlin strings provide excellent support for splitting and joining operations:
val csvData = "apple,banana,orange,grape"
val fruits = csvData.split(",")
println(fruits) // Output: [apple, banana, orange, grape]
val items = listOf("Kotlin", "Android", "JetBrains", "IntelliJ")
val joined = items.joinToString(" - ")
println(joined) // Output: Kotlin - Android - JetBrains - IntelliJ
Kotlin strings support flexible replacement operations for text modification:
val original = "Java is great, Java is powerful"
val modified = original.replace("Java", "Kotlin")
println(modified) // Output: Kotlin is great, Kotlin is powerful
val regex = "\\d+".toRegex()
val textWithNumbers = "I have 5 apples and 10 oranges"
val replaced = textWithNumbers.replace(regex, "many")
println(replaced) // Output: I have many apples and many oranges
Here’s a comprehensive example demonstrating various Kotlin string operations in a practical scenario:
fun main() {
// Creating different types of Kotlin strings
val appName = "Kotlin String Processor"
val version = "2.1.0"
val description = """
This application demonstrates
various Kotlin string operations
for educational purposes
""".trimIndent()
// String interpolation with Kotlin strings
val welcomeMessage = "Welcome to $appName v$version"
println("Application Info:")
println(welcomeMessage)
println("Description: ${description.replace("\n", " ")}")
// Working with user input simulation
val userInput = " HELLO kotlin programming WORLD "
println("\nProcessing user input: '$userInput'")
// Cleaning and formatting the Kotlin string
val cleanedInput = userInput.trim().lowercase()
val formattedInput = cleanedInput.split(" ")
.joinToString(" ") { word ->
word.replaceFirstChar { if (it.isLowerCase()) it.titlecase() else it.toString() }
}
println("Cleaned input: '$cleanedInput'")
println("Formatted input: '$formattedInput'")
// Kotlin string analysis
val analysisText = "Kotlin strings are powerful and flexible"
println("\nString Analysis for: '$analysisText'")
println("Length: ${analysisText.length}")
println("Word count: ${analysisText.split(" ").size}")
println("Contains 'powerful': ${analysisText.contains("powerful")}")
println("Starts with 'Kotlin': ${analysisText.startsWith("Kotlin")}")
println("First character: '${analysisText.first()}'")
println("Last character: '${analysisText.last()}'")
// Kotlin string manipulation for data processing
val csvData = "John,25,Developer;Jane,30,Designer;Bob,28,Manager"
println("\nProcessing CSV-like data:")
val employees = csvData.split(";").map { employee ->
val details = employee.split(",")
Employee(details[0], details[1].toInt(), details[2])
}
employees.forEach { employee ->
val info = "Name: ${employee.name}, Age: ${employee.age}, Role: ${employee.role}"
println(info)
}
// Advanced Kotlin string operations
val templateString = "Hello {name}, welcome to {platform} development!"
val personalizedMessage = templateString
.replace("{name}", "Developer")
.replace("{platform}", "Kotlin")
println("\nTemplate processing:")
println("Original: $templateString")
println("Personalized: $personalizedMessage")
// Kotlin string validation example
val emails = listOf("user@example.com", "invalid-email", "test@domain.org")
println("\nEmail validation:")
emails.forEach { email ->
val isValid = email.contains("@") && email.contains(".") &&
email.indexOf("@") < email.lastIndexOf(".")
println("$email - ${if (isValid) "Valid" else "Invalid"}")
}
}
// Data class for employee information
data class Employee(val name: String, val age: Int, val role: String)
Expected Output:
Application Info:
Welcome to Kotlin String Processor v2.1.0
Description: This application demonstrates various Kotlin string operations for educational purposes
Processing user input: ' HELLO kotlin programming WORLD '
Cleaned input: 'hello kotlin programming world'
Formatted input: 'Hello Kotlin Programming World'
String Analysis for: 'Kotlin strings are powerful and flexible'
Length: 39
Word count: 6
Contains 'powerful': true
Starts with 'Kotlin': true
First character: 'K'
Last character: 'e'
Processing CSV-like data:
Name: John, Age: 25, Role: Developer
Name: Jane, Age: 30, Role: Designer
Name: Bob, Age: 28, Role: Manager
Template processing:
Original: Hello {name}, welcome to {platform} development!
Personalized: Hello Developer, welcome to Kotlin development!
Email validation:
user@example.com - Valid
invalid-email - Invalid
test@domain.org - Valid
This comprehensive example showcases how Kotlin strings work in real-world scenarios, from basic string manipulation to complex data processing tasks. The code demonstrates string interpolation, cleaning operations, analysis functions, CSV processing, template replacement, and validation - all common use cases when working with Kotlin strings in application development.