String
These are the most important String methods (here, S and
T are strings):
- S.length is the length of the string in characters;
- S.substring(i) returns the part of the string starting at
index i.
- S.substring(i,j) returns the part of the string starting
at index i and going up to index j-1. You can write
S.slice(i,j) instead.
- S.contains(T) returns true if T is a
substring of S;
- S.indexOf(T) returns the index of the first occurrence of
the substring T in S (or -1);
- S.indexOf(T, i) returns the index of the first occurrence
after index i of the substring T in S (or -1);
- S.toLowerCase and S.toUpperCase return a copy of
the string with all characters converted to lower or upper case;
- S.capitalize returns a new string with the first letter only
converted to upper case;
- S.reverse returns the string backwards;
- S.isEmpty is the same as S.length == 0;
- S.nonEmpty is the same as S.length != 0;
- S.startsWith(T) returns true if S starts
with T;
- S.endsWith(T) returns true if S ends
with T;
- S.replace(c1, c2) returns a new string with all
characters c1 replaced by c2;
- S.replace(T1, T2) returns a new string with all
occurrences of the substring T1 replaced by T2;
- S.trim returns a copy of the string with white space at
both ends removed;
- S.format(arguments) returns a string where the
percent-placeholders in S have been replaced by the arguments
(see example below);
- S.split(T) splits the string into pieces and returns an
array with the pieces. T is a regular expression (not
explained here). To split around white space,
use S.split("
s+").
In addition, strings provide all the common methods of all
sequences—you can think of a string as a
sequence of characters.
For example:
scala> val S = "CS109 is nice"
S: java.lang.String = CS109 is nice
scala> S.contains("ice")
res0: Boolean = true
scala> S.indexOf("ice")
res1: Int = 10
scala> S.indexOf("rain")
res2: Int = -1
scala> S.replace('i', '#')
res4: java.lang.String = CS109 #s n#ce
scala> S.split("\\s+")
res5: Array[java.lang.String] = Array(CS109, is, nice)
scala> S.toLowerCase
res6: java.lang.String = cs109 is nice
scala> S.toUpperCase
res7: java.lang.String = CS109 IS NICE
scala> S.substring(5)
res8: java.lang.String = " is nice"
scala> S.substring(5,8)
res9: java.lang.String = " is"
scala> S.reverse
res10: String = ecin si 901SC
scala> val F = "%5s %3d %-3d %g"
F: java.lang.String = %5s %3d %-3d %g
scala> F.format("cs206", 12, 3, math.Pi)
res11: String = cs206 12 3 3.14159