String methods
The String class has dozens of methods. Here are the most useful ones: finding a substring, cutting out a part, changing case, replacing, splitting. Remember the main rule from the strings lesson: a string never changes, and every method returns a new one.
Searching in a string
contains() checks whether a string contains a substring, startsWith() and endsWith() whether it starts or ends with it. indexOf() returns the index of the first occurrence, or -1 if there is none:
void main() {
String email = "anna@example.com";
IO.println(email.contains("@"));
IO.println(email.endsWith(".com"));
IO.println(email.indexOf("@"));
IO.println(email.indexOf("#"));
}Output:
true
true
4
-1lastIndexOf() works the same way but finds the last occurrence.
substring
substring(start, end) cuts out part of a string: the character at index start is included, the one at index end is not. If no end is given, everything up to the end of the string is taken:
void main() {
String email = "anna@example.com";
int at = email.indexOf("@");
IO.println(email.substring(0, at));
IO.println(email.substring(at + 1));
}Output:
anna
example.comCase and whitespace
toUpperCase() and toLowerCase() change the case. strip() removes whitespace at both ends — often needed for user input:
void main() {
String input = " Oleg ";
IO.println("[" + input.strip() + "]");
IO.println(input.strip().toUpperCase());
IO.println("JAVA".toLowerCase());
}Output:
[Oleg]
OLEG
javaFor a case-insensitive comparison there is equalsIgnoreCase(): "Java".equalsIgnoreCase("JAVA") returns true.
replace
replace() replaces every occurrence of one substring with another:
void main() {
String phone = "555-123-4567";
IO.println(phone.replace("-", ""));
IO.println("cat and cat".replace("cat", "dog"));
}Output:
5551234567
dog and dogsplit and join
split() cuts a string at a separator and returns an array of the parts. String.join() does the opposite — it glues the parts together with a separator:
void main() {
String csv = "Anna,Oleg,Maria";
String[] names = csv.split(",");
IO.println(names.length);
IO.println(names[1]);
IO.println(String.join(" | ", names));
}Output:
3
Oleg
Anna | Oleg | Mariasplit() drops empty parts at the end: "a,b,,".split(",") gives an array of two elements.
Checks and repetition
isEmpty() is true for a zero-length string, isBlank() also for a string of only spaces. repeat() repeats a string a given number of times:
void main() {
IO.println("".isEmpty());
IO.println(" ".isEmpty());
IO.println(" ".isBlank());
IO.println("=".repeat(12));
}Output:
true
false
true
============Common mistake
String methods do not change the original string. If you do not store the result, it is simply lost:
void main() {
String name = "anna";
name.toUpperCase();
IO.println(name);
}Output:
annaAssign the result to a variable: name = name.toUpperCase();.