Kotlin – Strings


Kotlin – Strings

Kotlin uses string data types to store an array of characters. Double quotes must surround string values ("") or triple quotes
(" " ").

At Kotlin, we have two string types - one called the escaped string and the other called the raw string.

  1. The escaped string is declared in double quotes (“”), which may contain escape characters such as '\ n', '\ t', and '\ b'.
  2. The raw string is declared within the triple quote (“ “ “) and may contain multiple lines without escape characters.

It is optional to specify the data type for a string, and the code can tell if a variable is a string because of the given double or triple quotes.

To create a string variable without entering a value, you must specify the type when declaring the variable, or it will raise an error:

Kotlin String Templates

Kotlin string templates are the parts of the code evaluated and the results interpolated to the string. A template expression starts with a dollar sign ($) and may contain a name or phrase.

Kotlin String Object

The Kotlin string is an object with many properties and functions that can perform certain functions on strings by writing a dot character (.) after the specified string variable.

Kotlin String Indexes

Kotlin can be considered an array of string characters, or you can say it is an array of string characters. You can access an element by specifying the element's index using a square bracket.

String indexes start at 0, so if you want to access the fourth element of the string, you must specify index 3 to access the fourth element.

Kotlin String Length

The Kotlin String length property can be used to find the length of a codeine string. The Kotlin function count () also specifies the length of a given string.

Kotlin String Last Index

Let us use the last index property of the Kotlin string to find the index of the last character in the char sequence. If a string is empty, it returns -1.

Changing Case of Strings

Kotlin provides toUpperCase () and toLowerCase () functions to convert a string to uppercase and lowercase.

Kotlin String Concatenation

We can use the + operator to combine two strings, or we can use the plus () function to combine the two strings.

Trim Characters from a String

We can remove the first few or the last few characters from a string using the drop () or dropLast () functions.

Quotes inside a String

To use quotes within a string, use single quotes ('):

To Compare two Strings

Kotlin provides the compare To () function to compare two strings. This function returns 0 if the two strings are equal; otherwise, it returns 1.

Kotlin getOrNull () Function

If the character is out of range of the sequence, the Kotlin getOrNull () function returns a character that is either indexed or invalid.

Kotlin toString () Function

Kotlin toString () represents a string of a function object.