Strings and string interpolation |
To create a String object, write a string enclosed in double quotation marks. A string object is a sequence of characters, which can be accessed (but not changed) using an index:
>>> val h = "Hello World" >>> h Hello World >>> h[0] H >>> for (i in 0 until h.length) { print(h[i]); print('*') } H*e*l*l*o* *W*o*r*l*d* >>> h.indices 0..10 >>> for (i in h.indices) { print("${h[i].toInt()} ") } 72 101 108 108 111 32 87 111 114 108 100
Special characters can be placed in String literals (also in Char literals) using a backslash. For instance, \n is a new-line character, \t a tabulator, \' and \" are single and double quotes, and \\ is a backslash character:
>>> val p = "Hi\tWorld,\n how are \n we \"today\"?" >>> p Hi World, how are we "today"?
Another special character in string literals is the dollar sign, which is used for string interpolation. This means that you can insert the value of any variable or expression into the string value, like this:
>>> val a = "CS109" >>> val b = Math.PI / 2.0 >>> val c = (109 < 206) >>> "a = $a, b = $b, c = $c, \$a" a = CS109, b = 1.5707963267948966, c = true, $aThe value of each variable is converted to a string and inserted into the resulting string. To place a dollar sign in your string, you need to put a backslash in front of it.
Instead of variable values, one can use arbitrary expressions by putting them inside braces:
>>> "${a.length}, pi/2 = ${Math.PI / 2.0}, 109 < 206 is ${109 < 206}" 5, pi/2 = 1.5707963267948966, 109 < 206 is true
Kotlin also supports the triple-quote syntax from Python to create long strings possibly containing new-line characters. Inside triple-quote strings, the backslash has no special meaning, but the dollar sign still works:
>>> """This is \not a \test, ${a.length}, $a" ... ... $ \not "in quotes", 'in quotes' """ This is \not a \test, 5, CS109" $ \not "in quotes", 'in quotes'
Strings have many useful methods. Here are the most important ones (here, S and T are strings):
In addition, strings provide many of the methods of lists—you can think of a string as a sequence of characters.
For example:
>>> val S = "CS109 is nice" >>> S.contains("ice") true >>> "ice" in S true >>> S.indexOf("ice") 10 >>> S.indexOf("rain") -1 >>> S.replace('i', '#') CS109 #s n#ce >>> S.split(Regex("\\s+")) [CS109, is, nice] >>> S.toLowerCase() cs109 is nice >>> S.toUpperCase() CS109 IS NICE >>> S.substring(5) is nice >>> S.substring(5, 8) is >>> S.reversed() ecin si 901SC >>> val F = "%5s %3d %-3d %g" >>> F.format("cs206", 12, 3, Math.PI) cs206 12 3 3.14159
Strings and string interpolation |