You are currently viewing Kotlin String
string_in_kotlin

Kotlin String

What is String in kotlin?

In Kotlin, strings are represented by the String class, which is immutable. This means that once a String object is created, its value cannot be changed. Strings can be created using string literals enclosed in double quotes ("...") or triple quotes ("""...""") for raw strings.

val regularString = "Hello, Kotlin!"  

How to Create An String ?

1. String Literals

The most common way to create a string in Kotlin is by using string literals, which are enclosed in double quotes ("..."). String literals support escape characters such as \n (newline), \t (tab), \\ (backslash), and \" (double quote).

val str1 = "Hello, Kotlin!"
val str2 = "This is a string with escape characters: \n\t\\\""

2. Raw Strings

Kotlin also supports raw strings enclosed in triple quotes ("""..."""). Raw strings can span multiple lines and contain special characters without the need for escaping.

val rawStr = """
    This is a raw string
    Spanning multiple lines
    With support for "quotes" and \n escape sequences
"""

3. Using String Constructors

You can create strings using constructors provided by the String class.

Using Char Array charArrayOf
val charArray = charArrayOf('H', 'e', 'l', 'l', 'o')
val strFromCharArray = String(charArray)  // "Hello"

Here, charArrayOf('H', 'e', 'l', 'l', 'o') creates a CharArray containing the characters 'H', 'e', 'l', 'l', 'o'.

The String(charArray) constructor in Kotlin converts the CharArray (charArray) into a String. This constructor creates a new String object using the characters from the specified CharArray

From Byte Array (with Charset)
val byteArray = byteArrayOf(72, 101, 108, 108, 111)  // ASCII values for "Hello"
val strFromBytes = String(byteArray, Charsets.UTF_8)  // "Hello"

Here, byteArrayOf(72, 101, 108, 108, 111) creates a ByteArray containing the ASCII values corresponding to the characters 'H', 'e', 'l', 'l', 'o'.

The String(byteArray, Charsets.UTF_8) constructor in Kotlin creates a new String object using the bytes from the specified ByteArray, interpreting them as UTF-8 encoded characters.

Charsets.UTF_8 specifies the character encoding to be used when decoding the bytes into a string. UTF-8 is a popular encoding that can represent all Unicode characters efficiently.

From Char Array (with Offset and Length)
val charArray = charArrayOf('H', 'e', 'l', 'l', 'o', '!', '!', '!')
val strFromCharArray = String(charArray, 0, 5)  // "Hello"

The String(charArray, startIndex, endIndex) constructor in Kotlin creates a new String object using a portion of the specified CharArray.

here, String(charArray, 0, 5) creates a String starting from index 0 up to (but not including) index 5 in charArray. This means it takes the characters 'H', 'e', 'l', 'l', 'o' from charArray. Therefore, strFromCharArray will contain the string "Hello".

4. Using Factory Functions

Kotlin provides factory functions to create strings from other data types or sources.

toString() Function

It is used to obtain a string representation of an object.e. It returns a string that typically includes information about the object’s class and some meaningful data from its properties.

val number = 123
val strFromNumber = number.toString()  // "123"
String.format() Function

the String.format() function is used to create formatted strings by substituting specified values into placeholders within a format string. This function is similar to the printf() function in C and other programming languages.

The String.format() function has the following syntax:

public static String format(String format, Object... args)
  • format: A format string that contains placeholders (format specifiers) to be replaced with corresponding values from the args array.
  • args: Zero or more arguments that will be substituted into the placeholders in the format string.
Format Specifiers

The format string can contain placeholders specified using % followed by a format specifier. Each format specifier specifies how a corresponding argument should be formatted when substituted into the string. Some common format specifiers include:

  • %s: String
  • %d: Integer
  • %f: Floating-point number
  • %b: Boolean
  • %c: Character
  • %t: Date/time
val name = "Alice"
val age = 30
val formattedString = String.format("Name: %s, Age: %d", name, age)
println(formattedString)

In this example:

  • "Name: %s, Age: %d" is the format string containing two placeholders (%s for string and %d for integer).
  • name and age are provided as arguments to String.format().
  • The %s placeholder is replaced by the value of name (which is "Alice"), and %d is replaced by the value of age (which is 30).

String Interpolation and Templates

One of the powerful features of Kotlin strings is string interpolation, which allows embedding expressions directly into string literals using the ${...} syntax.

fun main() {
    val name = "Alex"
    val age = 30
    val message = "Hello, $name! You are $age years old."
    print(message)//Hello, Alex! You are 30 years old.
}

Accessing and Modifying Elements:

Accessing Elements:

Individual characters of a string elements can be accessed using indexing or specific methods.

val str = "Hello"
val firstChar = str[0] // 'H'

// Using get() function
val thirdChar = str.get(2) // 'l'

Modifying Elements:

To modify a string in Kotlin, you typically create a new string based on the original string and the desired modifications.

val original = "Hello"
val modified = original.substring(0, 4) + "p!" // "Help!"

You can use other string manipulation functions or extensions provided by Kotlin’s standard library for more complex modifications.

Common String Functions:

Kotlin provides useful functions and properties for string manipulation:

Length: The length property of a string returns the number of characters in the string.

val str = "Hello, Kotlin"
println(str.length)  // Output: 13

In this example, str.length returns 13 because the string “Hello, Kotlin” has 13 characters including spaces and punctuation.

Substring: The substring(startIndex: Int, endIndex: Int) function extracts a substring from the original string based on the specified startIndex (inclusive) and endIndex (exclusive).

val str = "Hello, Kotlin"
val substring = str.substring(7)  // "Kotlin"

In this example, str.substring(7) returns the substring starting from index 7 to the end of the string, which is “Kotlin”.

Replace: The replace(oldValue: CharSequence, newValue: CharSequence) function replaces occurrences of oldValue with newValue in a string.

val str = "Hello Kotlin"
val replacedStr = str.replace("Kotlin", "World")  // "Hello World"

Here, str.replace("Kotlin", "World") replaces the substring “Kotlin” with “World” in the string str.

Interpolation: You can directly interpolate simple variable values into a string using the $ sign followed by the variable name.

val name = "Alice"
val age = 30
val message = "Hello, my name is $name and I am $age years old."
println(message)  // Output: Hello, my name is Alice and I am 30 years old.
  • $name is replaced with the value of the name variable ("Alice").
  • $age is replaced with the value of the age variable (30).

Concatenation: The substring(startIndex: Int, endIndex: Int) function extracts a substring from the original string based on the specified startIndex (inclusive) and endIndex (exclusive).

val str1 = "Hello"
val str2 = "Kotlin"
val result = str1 + ", " + str2  // "Hello, Kotlin"

Here, str1 + ", " + str2 concatenates the strings “Hello”, “, “, and “Kotlin” to form the result “Hello, Kotlin”.

Splitting: The split(delimiter: String) function splits a string into substrings based on the specified delimiter and returns an array of substrings.

val str = "apple,orange,banana"
val fruits = str.split(",")  // ["apple", "orange", "banana"]

Here, str.split(",") splits the string str into substrings using , as the delimiter, resulting in ["apple", "orange", "banana"].

Trimming: The trim(), trimStart(), and trimEnd() functions remove leading and trailing whitespace characters from a string.

val str = "   Kotlin   "
val trimmedStr = str.trim()  // "Kotlin"

In this example, str.trim() removes the leading and trailing spaces from the string str, resulting in "Kotlin".

Case Conversion: The toUpperCase() and toLowerCase() functions convert a string to uppercase and lowercase, respectively.

val str = "Hello"
val uppercase = str.toUpperCase()  // "HELLO"
val lowercase = str.toLowerCase()  // "hello"

In this example, str.toUpperCase() converts the string str to uppercase, resulting in "HELLO", while str.toLowerCase() converts it to lowercase, resulting in "hello".

contains : The contains(substring: CharSequence) function checks if a string contains the specified substring.

val str = "Kotlin is awesome"
val containsKotlin = str.contains("Kotlin")  // true

Here, str.contains("Kotlin") returns true because the substring “Kotlin” is present in the string str.

Checking Start/End : The startsWith(prefix: String) and endsWith(suffix: String) functions check if a string starts or ends with the specified prefix or suffix, respectively.

val str = "Hello World"
val startsWithHello = str.startsWith("Hello")  // true
val endsWithWorld = str.endsWith("World")  // true

In this example, str.startsWith("Hello") returns true because the string str starts with “Hello”, and str.endsWith("World") returns true because it ends with “World”.

Padding: The padStart(minLength: Int, padChar: Char) and padEnd(minLength: Int, padChar: Char) functions pad a string to a minimum length using the specified padChar.

val str = "123"
val paddedStr = str.padStart(5, '0')  // "00123"

Here, str.padStart(5, '0') pads the string str with leading zeros ('0') to make its length at least 5, resulting in "00123".

Concatenation : Strings can be concatenated using the + operator or the plus() function.

val str1 = "Hello"
val str2 = "Kotlin"
val result = str1 + ", " + str2  // "Hello, Kotlin"

Mutable Strings: If you need mutable strings for frequent modifications, you can use StringBuilder. especially for tasks like concatenation or appending new content.

val mutableStr = StringBuilder("Hello")
mutableStr.append(" World")
print(mutableStr) // "Hello World"

Also Read :