Kotlin String Class

Introduction

In Kotlin, the String class represents a sequence of characters. Strings are immutable, meaning that once a string is created, it cannot be changed. The String class provides a variety of methods and properties to perform operations on strings, such as manipulation, comparison, and searching.

Table of Contents

  1. What is the String Class?
  2. Creating Strings
  3. String Operations
  4. String Functions
  5. Examples of String
  6. Real-World Use Case
  7. Conclusion

1. What is the String Class?

The String class in Kotlin is used to represent textual data. A string is a sequence of characters enclosed within double quotes. Strings in Kotlin are immutable and can contain characters from the Unicode character set.

Syntax

val myString: String = "Hello, Kotlin!"

2. Creating Strings

You can create strings in Kotlin using string literals, string templates, and raw strings.

String Literals

val str: String = "Hello, World!"

String Templates

val name = "John"
val greeting = "Hello, $name!"

Raw Strings

val rawString = """
    This is a
    raw string.
""".trimIndent()

3. String Operations

Kotlin supports various operations on String values, including concatenation, comparison, and access characters.

Concatenation

You can concatenate strings using the + operator or string templates.

val str1 = "Hello"
val str2 = "World"
val result = str1 + ", " + str2 + "!"

Comparison

You can compare strings using the == operator for structural equality and the === operator for referential equality.

val str1 = "Hello"
val str2 = "Hello"
println(str1 == str2) // true
println(str1 === str2) // false, if they are different objects

Accessing Characters

You can access characters in a string using the index operator.

val str = "Kotlin"
val firstChar = str[0]

4. String Functions

The String class provides several useful functions:

  • length: Returns the length of the string.
  • substring(startIndex: Int, endIndex: Int): Returns a substring.
  • toUpperCase(): Converts the string to uppercase.
  • toLowerCase(): Converts the string to lowercase.
  • trim(): Removes leading and trailing whitespace.
  • split(delimiter: String): Splits the string into a list of substrings.
  • replace(oldValue: String, newValue: String): Replaces occurrences of a substring.
  • contains(other: CharSequence): Returns true if the string contains the specified substring.
  • startsWith(prefix: String): Checks if the string starts with the specified prefix.
  • endsWith(suffix: String): Checks if the string ends with the specified suffix.
  • indexOf(char: Char): Returns the index of the first occurrence of the specified character.
  • lastIndexOf(char: Char): Returns the index of the last occurrence of the specified character.
  • isEmpty(): Checks if the string is empty.
  • isNotEmpty(): Checks if the string is not empty.
  • isBlank(): Checks if the string is blank (contains only whitespace).
  • isNotBlank(): Checks if the string is not blank.
  • toInt(): Converts the string to an integer.
  • toDouble(): Converts the string to a double.
  • toFloat(): Converts the string to a float.
  • toBoolean(): Converts the string to a boolean.
  • toCharArray(): Converts the string to a character array.
  • compareTo(other: String): Compares the string to another string.
  • matches(regex: String): Checks if the string matches the specified regex.
  • replace(regex: Regex, replacement: String): Replaces occurrences of the specified regex with the replacement string.
  • take(n: Int): Returns the first n characters of the string.
  • drop(n: Int): Returns the string after dropping the first n characters.
  • repeat(n: Int): Returns a new string which is a repetition of the original string n times.

Example

fun main() {
    val str = "Hello, Kotlin!"

    println("Length: ${str.length}")
    println("Substring: ${str.substring(7, 13)}")
    println("Uppercase: ${str.toUpperCase()}")
    println("Lowercase: ${str.toLowerCase()}")
    println("Trim: ${str.trim()}")
    println("Split: ${str.split(", ")}")
    println("Replace: ${str.replace("Kotlin", "World")}")
    println("Contains 'Kotlin': ${str.contains("Kotlin")}")
    println("Starts with 'Hello': ${str.startsWith("Hello")}")
    println("Ends with '!': ${str.endsWith("!")}")
    println("Index of 'K': ${str.indexOf('K')}")
    println("Last index of 'o': ${str.lastIndexOf('o')}")
    println("Is empty: ${str.isEmpty()}")
    println("Is not empty: ${str.isNotEmpty()}")
    println("Is blank: ${str.isBlank()}")
    println("Is not blank: ${str.isNotBlank()}")
    println("To int: ${"123".toInt()}")
    println("To double: ${"123.45".toDouble()}")
    println("To float: ${"123.45".toFloat()}")
    println("To boolean: ${"true".toBoolean()}")
    println("To char array: ${str.toCharArray().contentToString()}")
    println("Compare to 'Hello, Kotlin!': ${str.compareTo("Hello, Kotlin!")}")
    println("Matches regex '\\w+': ${str.matches("\\w+".toRegex())}")
    println("Replace regex '\\w+': ${str.replace("\\w+".toRegex(), "Replaced")}")
    println("Take 5: ${str.take(5)}")
    println("Drop 7: ${str.drop(7)}")
    println("Repeat 3 times: ${str.repeat(3)}")
}

5. Examples of String

Example 1: Splitting a String

This example demonstrates how to split a string into a list of substrings.

fun main() {
    val str = "apple,banana,orange"
    val fruits = str.split(",")
    println(fruits)
}

Output:

[apple, banana, orange]

Example 2: Checking for Substring

This example demonstrates how to check if a string contains a substring.

fun main() {
    val str = "Hello, Kotlin!"
    println(str.contains("Kotlin")) // true
}

Example 3: Replacing a Substring

This example demonstrates how to replace a substring with another string.

fun main() {
    val str = "Hello, Kotlin!"
    val newStr = str.replace("Kotlin", "World")
    println(newStr) // Hello, World!
}

Example 4: Converting String to Different Types

This example demonstrates how to convert a string to different numeric types.

fun main() {
    val numStr = "123"
    println(numStr.toInt()) // 123
    println(numStr.toDouble()) // 123.0
    println(numStr.toFloat()) // 123.0
}

Example 5: String Template

This example demonstrates how to use string templates.

fun main() {
    val name = "John"
    val age = 30
    val greeting = "My name is $name and I am $age years old."
    println(greeting)
}

Output:

My name is John and I am 30 years old.

6. Real-World Use Case: Validating Email Address

In a real-world scenario, you might need to validate an email address using regular expressions.

Example: Validating Email Address

fun isValidEmail(email: String): Boolean {
    val emailRegex = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+
quot;.toRegex()
    return email.matches(emailRegex)
}

fun main() {
    val email = "example@example.com"
    println("Is valid email: ${isValidEmail(email)}") // true
}

Conclusion

The String class in Kotlin provides a variety of methods to manipulate, compare, and search strings. Understanding how to use these methods effectively can greatly enhance your ability to work with textual data in Kotlin. Whether you are performing simple string operations or complex text processing, the String class offers the tools you need to get the job done.

Comments