Manuipulating and Operating on Strings
Working with the String Class
Strings are collections of characters. A single string can contain zero, one or more characters, strung together.
You can find information about Strings here.
Kotlin has a rich String class that provides the means to manipulate, analyse and work with strings of characters. The full list of String class functions is here.
Defining Strings
Strings are defined using "..." quotes:
val forename = "Jimmy"
val surname = "Smith"
val greeting = "Why, hello there!"
If you need strings that contain multiple lines of text, you can use "'" triple quotes at the start and end:
val message =
"""Hello to all of you!
Welcome to the new term.
Enjoy your time here."""
Concatenation (Joining) Strings
To join different strings or string variables, use the concatenation operator:
+
- Concatenation ('joining' text together)
val forename = "Jimmy"
val surname = "Smith"
val fullName = "Mr " + forename + " " + surname
println("Hello, " + fullName)
Note that often it is clearer and easier to use String Templates when displaying several variables together (see next section). However, sometimes concatenation is better (e.g. if joining many items over several lines of code).
String Templates
Variable values can be easily added into other text using String Templates. Variables are simply placed into the string preceded by a $ symbol:
val forename = "Jimmy"
val surname = "Smith"
val fullName = "Mr $forename $surname"
println("Hello, $fullName!") // Hello, Jimmy Smith!
Function calls, etc. can also be placed inside a string, but must be wrapped in {...} brackets:
val fullName = "Mr ${forename.get(0)} $surname"
println("Hello, $fullName!") // Hello, J Smith!
Excaped Characters
Some characters are not possible to type (e.g. a newline), or have special meaning in strings (e.g. the $ symbol for String Templates). In these cases we use excaped characters using the \ character:
\n
- Inserts a newline character
\$
- Inserts the $ symbol (instead of a variable)
\"
- Shows a " symbol (instead of ending the string)
\\
- Shows a \ symbol (instead of escaping next char)
"I shouted \"Hello!\" to her" // Shows speech marks
"Line One\nLine Two" // Adds newlines
"It costs \$200 to buy" // Showss the $ symbol
Altering Strings
The String class has built-in functions to manipulate a string. Here are some useful ones:
.toUpperCase()
- Returns an all uppercase version
.toLowerCase()
- Returns an all lowercase version
.reversed()
- Returns a reversed version
Note that none of these functions modify the original string, they just return a new string with the required content.
val name= = "Jimmy Smith"
name.toUpperCase() // "JIMMY SMITH"
name.toLowerCase() // "jimmy smith"
name.reversed() // "htimS ymmiJ"
String Properties and Information
The String class has built-in properties and functions that give information about the string contents. Here are some useful ones:
.length
- Returns length of the string, including spaces
.isEmpty()
- Returns true if contains nothing
.isNotEmpty()
- Returns true if contains any characters
.isNotBlank()
- Returns true if contains text/symbols
.contains(text)
- Returns true if given text is found
.startsWith(text)
- Returns true if starts with given text
.endsWith(text)
- Returns true if ends with given text
.indexOf(char)
- Returns the index of first matching character
.count(match)
- Returns number of times the match occurs
val name= = "Jimmy Smith"
name.length // 11
name.isEmpty() // false
name.isNotEmpty() // true
name.isNotBlank() // true
name.contains("S") // true
name.contains("s") // false
name.contains("Smith") // true
name.startsWith("Jim") // true
name.startsWith("y") // false
name.endsWith("Jim") // false
name.endsWith("y") // true
name.indexOf('S') // 6
name.indexOf('X') // -1 (no match)
name.count{ it == 'm' } // 3
Extracting Text from Strings
The String class has built-in functions to get individual characters or chunks of text from within a string. Here are some useful ones:
.firstOrNull()
- Returns first character, null if none
.lastOrNull()
- Returns last character, null if none
.get(n)
- Returns character at index n (index starts at 0 for first character)
.take(n)
- Returns the first n characters
.takeLast(n)
- Returns the last n characters
.drop(n)
- Removes the first n characters and returns rest
.dropLast(n)
- Removes the last n characters and returns rest
.substring(r)
- Returns part of the string based on the given index or range (see examples)
Note that none of these functions modify the original string, they just return a new string with the required content.
val name= = "Jimmy Smith"
name.firstOrNull() // 'J'
name.lastOrNull() // 'h'
name.get(4) // 'y'
name.take(3) // "Jim"
name.takeLast(3) // "ith"
name.drop(3) // "my Smith"
name.dropLast(3) // "Jimmy Sm"
name.substring(0, 3) // "Jim" (3 not included)
name.substring(0..3) // "Jimm" (3 included)
name.substring(6..8) // "Smi" (8 included)
name.substring(6) // "y Smith" (6 to end)
name.substring(-4) // "mith" (from end, back 4)
Breaking Apart Strings
The String class has several built-in functions to seperate out words or individual characters from a string. Here are some useful ones:
.toCharArray()
- Returns a collection of all of the characters from the string
.split(char)
- Splits the string each time the given character is found and returns a collection of the parts
Note that none of these functions modify the original string, they just return a new collection of characters or strings.
val name= = "Jimmy Smith"
name.toCharArray() // ['J','i','m','m','y'...]
name.split(' ') // ["Jimmy", "Smith"]