Strings in Kotlin are sequences of characters enclosed within double quotes (" "
). They are used to represent textual data and are one of the fundamental data types in Kotlin. Here's a simple explanation with examples:
You can declare strings by simply enclosing text within double quotes.
Example
val message = "Hello, Kotlin!"
String interpolation allows you to embed expressions or variables within a string.
Example
val name = "Alice"
val age = 30
val greeting = "My name is $name and I am $age years old."
You can use escape characters like \n
for newline, \t
for tab, \"
for double quote, \'
for single quote, and \\
for backslash within strings.
Example
val escapedString = "This is a new line\nThis is a tab\tThis is a \"quote\""
Kotlin provides powerful string templates that allow you to execute expressions within a string literal.
Example
val a = 10
val b = 5
val sum = "The sum of $a and $b is ${a + b}"
You can create multiline strings using triple double quotes (""" """
).
Example
val multilineString = """
This is a multiline
string in Kotlin.
It can span multiple lines.
"""
Kotlin provides a variety of built-in functions to work with strings, such as length
, toUpperCase
, toLowerCase
, substring
, contains
, startsWith
, endsWith
, etc.
Example
val str = "Hello, World!"
val length = str.length // 12
val upperCase = str.toUpperCase() // "HELLO, WORLD!"
val lowerCase = str.toLowerCase() // "hello, world!"
val subString = str.substring(0, 5) // "Hello"
val contains = str.contains("World") // true
Strings are essential for working with textual data in Kotlin. With string interpolation, escaping characters, string templates, and various string functions, Kotlin provides powerful features to manipulate and work with strings efficiently.