Standard functions for working with strings in Kotlin

There are several standard functions in Kotlin that are designed to solve common tasks more efficiently and easily. These functions are part of the Kotlin standard library and can be used directly in code. In the following chapters, we will look at commonly used standard functions for working with strings, mathematical operations, arrays, collections, and date and time. The syntax and functionality are explained for each function and common use case examples are given.

Some of the most useful and commonly used functions for the strings are:

toUpperCase() and toLowerCase()

Features toUpperCase () and toLowerCase () convert a string to upper or lower case.

In this example, the default function toUpperCase () called on the object pointed to by the variable mystring to convert all letters in the string to uppercase. The call is made by appending the function name toUpperCase to the variable name with a dot operator, followed by the arguments in parentheses. In this case, no other arguments were passed to the function, so the parentheses are empty.

The toLowerCase() function achieves the opposite: all letters in a string are converted to lowercase:

Application example: The functions toUpperCase () and toLowerCase () can be used to normalize user input. Often users enter data in different notations, e.g. B. when entering email addresses or user names. To ensure that data is stored and processed consistently, can toLowerCase () or toUpperCase () used to convert all characters to lowercase or uppercase before storing them in a database or using them for further processing.

capitalize() and decapitalize()

The capitalize(), decapitalize() functions change the first letter of a string to uppercase or lowercase.

Application example: The functions capitalize () and Decapitalize () can be used to ensure that text has the desired formatting (e.g. salutation in a letter or title in a heading).

trim ()

The function trim () removes spaces at the beginning and end of a string.

Application example: A common use case for the trim ()-Function is the cleaning of user input or text data from external sources. This removes unwanted spaces at the beginning and end of the string to avoid possible formatting problems or incorrect data processing.

The above example represents such a case: the user entered his name with two spaces at the beginning and at the end - 'Donald Firestone'. With the help of trim ()function, the unnecessary spaces have been removed, leaving only the name actually entered.

trimStart() and trimEnd()

Standard functions trimStart() and trimend () remove spaces only at the beginning or end of a string.

substring ()

The function substring () returns part of the string defined by the specified range.

In this example the substring ()function on the String object mystring called. The parameters are 4 and 19 passed to extract a substring (substring) from the original string. The first number 4 is the starting index (inclusive), and the second number 19 is the final index (exclusive). In this case the substring is from the index 4 up to the index 18 extracted.

Application example: When working with dates and times in text form substring () can be used to extract specific parts such as year, month or day from a date string.

replace ()

The function replace () replaces all occurrences of a character or string in the string with a different value.

In this code example, the word 'world' in the original string 'Hello, world!' through the word 'Kotlin' replaced, and the result 'Hello, Kotlin!' is output on the console.

Example application for censorship of inappropriate content: When processing user input or text content, it may be necessary to automatically censor inappropriate words. For that can replace ()function can be used to replace such words with suitable wildcards or special characters/stars.


The standard function contains() checks whether a string contains a specific character or string.

Application example validation of user input: If the user input needs to be validated, e.g. B. to ensure that an email address contains an “@” symbol or a password contains certain characters, the contains()function can be used to check these requirements.

startsWith() and endsWith()

The standard functions startsWith() and Endswith () check whether a string begins or ends with a specific prefix or suffix.

Application examples:

  • By the use of startsWith() The application can check whether a URL is using 'https://' begins and thus confirms that the data is encrypted.
  • An example for Endswith () is filtering files by their file type. If an application has many files in a directory and only needs files of a certain type (e.g. only images or only PDFs), endsWith() can be used to filter only files that end with the appropriate file extension (e.g. '.jpg' or '.pdf').

split ()

The function split () splits a string into a list of substrings separated by one or more separators.

Application example: An example of the use of split () is the analysis of user input, such as: B. Telephone numbers. When a user enters a phone number, the application can split ()-Use function to split the phone number into different parts, such as: B. the country code, the area code and the actual telephone number. The individual parts can then be further processed or validated to ensure they are correct.

Jointostring ()

The function Jointostring () combines elements of a collection or array into a string with optional separators, prefixes and suffixes.

Application example: An example of the use of Jointostring () is the combining of elements of a list or array into a string with a specific separator. For example, if an application has a list of users and wants to display them in a user interface, it can Jointostring () can be used to convert the list into a comma separated string that is easily readable by the user.


The standard plus() function joins two strings together.

Application example: An example of the use of plus() is the creation of personalized messages. If an application has user information such as the user's name and age, it can plus() be used to create a personalized message containing this information.

take(), takeLast(), drop(), dropLast()

take(), takeLast(), drop(), dropLast() returns the first or last characters of a string or removes the first or last n characters of a string.

Application examples:

  • take(): Extract the first n words from a text to create a preview or summary.
  • takeLast(): Get the last n characters of a string, for example the last four digits of a credit card number or a phone number, to partially mask them.
  • Drop (): Remove a prefix from filenames or text strings to apply a new naming convention or remove unwanted prefixes.
  • dropLast(): Remove the file extension of a filename to get the base name.

indexOf() and lastIndexOf()

indexOf () and lastIndexOf () returns the index of the first or last occurrence of a character or string in the string. Returns -1 if the value is not found. 

In this code example, the indexOf ()function mystring called at the first index of the substring 'Homer' in mystring to find. In this case lies 'Homer' at the index 21 (string indexing starts at 0).

Then the lastIndexOf ()function mystring called at the last index of the substring 'dear' in mystring to find. There 'dear' twice in mystring occurs, finds lastIndexOf () the index of the second occurrence, which is at index 16 lies.

Application examples:

  • indexOf (): Check whether a text contains certain keywords or phrases and find their position to format the text for display or processing.
  • lastIndexOf (): Find the last delimiter in a file path or URL to extract the file name or the last section of a URL.

isNullOrEmpty() and isNullOrBlank()

isNullOrEmpty() and Isnullorblank () checks whether a string consists of null or empty or null or only spaces.

In this example, a nullable String-Variable named mystring declared and her the value null assigned. 

The isNullOrEmpty()-Function is on mystring called. This function checks whether the string passed in is either null or empty (that is, contains no characters). There mystring the value null has, returns the function true .

The Isnullorblank ()-Function is on mystring called. This function checks whether the string passed in is either null or consists only of spaces, tabs or line breaks. There mystring the value null also gives the function true .

Application examples:

  • isNullOrEmpty(): Validate user input in forms to ensure required fields are populated and do not contain empty strings.
  • Isnullorblank (): Validate user input in forms to ensure required fields are not just spaces, tabs, or line breaks.

padStart() and padEnd()

The function pathStart() is used to pad a string at the beginning (left) to a specific length. It has two parameters: 

  • length – The desired total length of the padded string.
  • padChar – The character with which the string will be padded (optional, default is the space character ' ').

In this example the string 'Betty' with hyphens to a total length of 10 characters.

The function padEnd() is used to pad a string at the end (right) to a specific length. It also has two parameters:

  • length – The desired total length of the padded string.
  • padChar – The character with which the string will be padded (optional, default is the space character ').

In this example the string 'Betty' with hyphens at the end to a total length of 10 characters.

Application examples:

  • padStart(): Formatting numeric values, e.g. B. adding leading zeros to numbers to achieve an even number of digits (e.g. for product codes, invoice numbers, etc.).
  • padEnd(): Extending strings to a specific length to meet the needs of an API or database.

reversed ()

reversed() reverses the order of characters in a string.

Application example: Reversing strings to create special text effects or encodings, such as: B. when creating puzzles or simple cryptographic algorithms.


The repeat()function repeats a string n times.

Application example: Repetition of text elements or phrases to create artistic effects, animations or design elements.

Leave a Comment

Your e-mail address will not be published. Required fields are marked with * marked