Strings
Published Jan 11, 2023Updated Oct 24, 2023
Contribute to Docs
Strings are immutable objects that represent a sequence of characters contained within double quotes (""
).
Syntax
val stringName: String = "string value"
In Kotlin, string values are always defined as instances of the String
class.
String Templates
Templates can also be used to dynamically produce string values. Dynamic values don’t have to start as strings, and can either be directly referenced with a dollar sign ($
) or evaluated as a string with additional curly braces ({}
).
Example
The following example showcases the various ways strings are used in Kotlin:
fun main(args: Array<String>) {// String literalsval greeting: String = "Hello, World!"println(greeting)// String templatesval dynamicValue = 4val stringOne: String = "The value of dynamicValue is $dynamicValue"System.out.println(stringOne)val a = dynamicValueval b = 5val stringTwo: String = "The sum of a and b is ${a + b}"System.out.println(stringTwo)}
The output for the above code will be:
Hello, World!The value of dynamicValue is 4The sum of a and b is 9
String Methods
The following methods are convenient tools for handling a range of string related operations.
Strings
- .compareTo()
- Compares two strings lexicographically.
- .drop()
- Returns a string where the characters have been removed from the start to the nth index given.
- .dropLast()
- Returns a string with the last n characters removed.
- .endsWith()
- Returns a boolean value representing whether the sequence ends with the specified suffix.
- .filter()
- Filters elements from a collection based on a given predicate.
- .filterNot()
- Returns all elements of the original sequence not present in the predicate.
- .lowercase()
- Converts a string to lowercase.
- .padEnd()
- Pads a string using specified characters.
- .padStart()
- Pads the start of a string with the specified character.
- .partition()
- Returns two strings from the characters in the parameter string that satisfy a given predicate.
- .prependIndent()
- Adds indentation to a string.
- .regionMatches()
- Checks if a specified region within a Kotlin String matches the content of another string.
- .removePrefix()
- Removes a specified prefix from a Kotlin string, if present.
- .removeRange()
- Removes a range of characters from a Kotlin string.
- .removeSuffix()
- Removes a specified suffix from a Kotlin string, if present.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.