In computer programming, a string is traditionally a sequence of characters, either as a literal constant or as some kind of variable. In this tutorial, you’ll learn about strings in kotlin programming. You’ll learn to declare them, initialize them. Kotlin strings are exactly the same things as Java strings. You can pass a string created in kotlin Kotlin code to any Java method, and you can use any Kotlin standard library methods on strings that you receive form Java code. No conversion is involved, and no additional wrapper objects are created.
Format to declare a string in Kotlin
You can define a string by assigning a value to it. In this example the last line assigns a string value “inspire_coding” to the variable name.
You can combine the two statement in one statement. This way we declare and define a string variable in same statement.
In Kotlin mentioning data type String is optional. If we don’t mention the data type of the variable, then data type of variable is same as data type of the value being assigned to it. Since “inspire_coding” value has data type String, type of variable name is also String.
Array of Characters
String is an Array of Characters. You can access it using indexing operation.
You can concatenate Kotlin string values using + operator. It is possible with other data types as well. This is valid only if first value in the expression is a type of String.
String Literals In Kotlin
A string literal or anonymous string is a type of literal in programming for the representation of a string value within the source code of a computer program. Most often in modern languages this is a quoted sequence of characters (formally “bracketed delimiters”) As in x = “foo”, where “foo” is a string literal with value foo. The quotes are not part of the value.
Escaped String Literals
Escaped strings may have escape characters in them.
inspire_coding inspire_coding inspire_coding
Here is a list of escape characters supported in Kotlin
- \t – Inserts tab
- \b – Inserts backspace
- \n – Inserts newline
- \r – Inserts carriage return
- \’ – Inserts single quote character
- \” – Inserts double quote character
- \\ – Inserts backslash
- \$ – Inserts dollar character
Raw String Literals
Raw string is delimited by triple quote (“””) . It contains no escaping. It can contain newlines and any other characters.
Notice that the empty whitespace before Hello and after World! You can trim such whitespaces using trimMargin() function.
By default, trimMargin() function uses | as margin prefix. You can change it by passing a new string to this function.
I hope the description was understandable and clear. But if you have still questions, then leave me comments below! 😉
Have a nice a day! 🙂