To share this page click on the buttons below;
Strings
To define a string use String type, to access a character of the string, use index []
operator or the member function get(<index>)
.
<string>:String = "This is a string"
<string>[3] // is equal to s
<string>.get(3) // is equal to s
String are immutable, modifying a string means to create a new one.
Escape sequences
Escape | Charater |
---|---|
\t | tab |
\b | bell |
\r | carriage return |
\n | line feed |
\' | ' |
\" | " |
\ | \ |
\$ | $ |
Concatenate
- Use operator
+
- Use string template (see below)
- Use string builder (see below)
String template
When a string variable is put into another string preceded by $
the content of the string is substituted.
It is also possible to enclose expressions in curly brackets preceded by $
, in this case the expression is evaluated and "converted" to string.
a:String = "This is a string"
b:String = "$a too" // result is: "This is a string too"
c:String = "Result is ${3 * 3}" // result is: "Result is 9"
String builder
Example:
val str1 = "first string"
val str2 = " second string"
val sb = StringBuilder()
sb.append(str1).append(str2)
val str4 = sb.toString() //result is: "first string second string"
println("$str4\n")
Raw strings
- Are multi-line string defined using triple
"
. - Support String template
- Do not support escape sequences
- Are somehow "literal": this means that indentation spaces are put into the raw string. A possible solution for that problem (i.e. using indented multi-line raw string and avoid that indentations spaces come up into the string) is to use the
TrimMargin
String member function: this function removes all leading whitespace up to a certain character (by default this character is|
), also that character is removed from the string.
For example with:
val multi = """This is
an indented multi-line raw string
plus some stuff to get long
multi-line example"""
println("$multi\n")
val multi1 = """In this case we avoid
the indentation of the multi-line raw string
plus some stuff to get long
multi-line example"""
println("$multi1\n")
val multi2 = """Or you can indent and trim the
|the indentation of the multi-line raw string
|plus some stuff to get long
|multi-line example""".trimMargin()
println("$multi2\n")
you get
String length
<string>.lenght
Compare string
Method 1:
<string1>.equals(<string2>)
returns true
or false
Method 2:
<string1> == <string2>
Method 3:
<string1>.compareTo(<string2>)
Returns:
- 0 if
<string1>
is equal to<string2>
- a negative number if
<string1>
it's less than<string2>
- a positive number if
<string1>
it's greater than<string2>
Get a substring
<string>.subSequence(<from index>, <to index>)
<from index>
is included
<to index>
is excluded
Is sub-string contained?
<string1>.contains(<string2>)
return true
if <string1>
contains <string2>
To share this page click on the buttons below;