Kotlin Tutoial

Basics

Control Flow

Array & String

Functions

Collections

OOPs Concept

Exception Handling

Null Safety

Regex & Ranges

Java Interoperability

Miscellaneous

Android

Kotlin String

Strings are one of the most widely used data types in any programming language, and Kotlin provides a rich API for string manipulation. Here's a comprehensive tutorial on strings in Kotlin:

1. String Basics:

In Kotlin, strings are represented by the String class.

val name = "Alice"
val message = String(charArrayOf('H', 'e', 'l', 'l', 'o'))

Strings are immutable in Kotlin, which means once a string object is created, it cannot be changed.

2. String Literals:

Kotlin has two types of string literals:

  • Escaped strings: They may have escaped characters in them.

    val s1 = "Hello, World!\n"
    
  • Raw strings: They can contain newlines and arbitrary text. They're delimited by triple quotes (""").

    val s2 = """
        This is a string
        that spans multiple lines
        in the source code.
    """
    

3. String Templates:

You can use expressions inside string literals using the $ symbol.

val name = "Alice"
println("Hello, $name!") // Outputs: Hello, Alice!

For more complex expressions, use ${}:

val a = 5
println("Square of $a is: ${a * a}") // Outputs: Square of 5 is: 25

4. Common String Operations:

  • Length:

    val length = name.length
    
  • Concatenation:

    val combined = name + " Wonderland"
    
  • Substring:

    val sub = name.substring(1..3) // Outputs: "lic"
    
  • Comparison:

    val isEqual = name.equals("ALICE", ignoreCase = true) // true
    
  • Conversion:

    val upper = name.toUpperCase()
    val lower = name.toLowerCase()
    
  • Splitting:

    val words = "Kotlin is fun".split(" ") // [Kotlin, is, fun]
    
  • Trimming:

    Raw strings often contain additional newlines, you can remove them:

    val trimmed = s2.trimMargin()
    

5. String Interpolation:

As we've seen before, you can embed any valid Kotlin expression inside string literals:

val price = 10
println("Price is: $price") // Outputs: Price is: 10
println("Total price: ${price * 2}") // Outputs: Total price: 20

6. Multiline Strings:

In raw strings, you can also set the margin character and reference it in trimMargin(). The default character is |.

val text = """
    |Tell me and I forget.
    |Teach me and I remember.
    |Involve me and I learn.
""".trimMargin()

7. Escape Characters:

In escaped strings, special characters can be escaped using a backslash \.

val sentence = "She said, \"Kotlin is great!\"" 

8. String Elements:

You can iterate over a string just like a collection:

for (char in name) {
    println(char)
}

Conclusion:

Kotlin offers a robust and concise set of tools for string manipulation, making many tasks easier and more intuitive than in some other languages. By combining string literals, interpolation, and the Kotlin standard library's string extension functions, you can handle most string-related tasks effortlessly.

  1. Creating strings in Kotlin:

    • Strings can be created using double-quoted or triple-quoted syntax.
    val singleLine = "Hello, Kotlin!"
    val multiLine = """
        This is a multiline
        string in Kotlin.
    """
    
  2. String concatenation in Kotlin:

    • Concatenate strings using the + operator or the plus function.
    val greeting = "Hello"
    val name = "Kotlin"
    val message = greeting + ", " + name + "!"
    
  3. String interpolation in Kotlin:

    • Embed variables directly into strings using the $ symbol.
    val age = 25
    val info = "I am $age years old."
    
  4. String templates in Kotlin:

    • Utilize string templates for more complex expressions.
    val x = 10
    val y = 20
    val result = "The sum of $x and $y is ${x + y}."
    
  5. String methods and functions in Kotlin:

    • Access various string methods like length, toUpperCase, toLowerCase, etc.
    val text = "Kotlin"
    val length = text.length
    val uppercase = text.toUpperCase()
    
  6. Substring extraction in Kotlin:

    • Extract substrings using substring function.
    val original = "Hello, Kotlin!"
    val substring = original.substring(7, 13)
    
  7. String length and indices in Kotlin:

    • Get the length of a string and access characters by index.
    val text = "Kotlin"
    val length = text.length
    val firstChar = text[0]
    
  8. String comparison in Kotlin:

    • Compare strings using == for content equality or compareTo for lexicographical ordering.
    val str1 = "abc"
    val str2 = "def"
    val isEqual = str1 == str2
    
  9. Working with multiline strings in Kotlin:

    • Preserve formatting in multiline strings.
    val multiline = """
        Line 1
        Line 2
    """.trimIndent()
    
  10. String formatting in Kotlin:

    • Use formatting functions for more controlled output.
    val pi = 3.14159
    val formatted = "The value of pi is %.2f".format(pi)
    
  11. Regex and pattern matching with strings in Kotlin:

    • Leverage regular expressions for pattern matching.
    val input = "Kotlin123"
    val regex = "\\d+".toRegex()
    val hasDigits = regex.containsMatchIn(input)
    
  12. Null safety and strings in Kotlin:

    • Handle null strings safely using the safe call operator ?..
    val nullableString: String? = null
    val length = nullableString?.length ?: 0