Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Learn kotlin Strings


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:

Declaring Strings

You can declare strings by simply enclosing text within double quotes.

Example

val message = "Hello, Kotlin!"

String Interpolation

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."

Escaping Characters

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\""

String Templates

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}"

Multiline Strings

You can create multiline strings using triple double quotes (""" """).

Example

val multilineString = """
This is a multiline
string in Kotlin.
It can span multiple lines.
"""

String Functions

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

Conclusion

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.

Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java