4.5 String Transforming and Splitting
String methods return new strings. They do not change the original string.
String raw = " Java ";
String clean = raw.trim();
System.out.println(raw); // " Java "
System.out.println(clean); // "Java"trim() and strip()
trim() removes leading and trailing whitespace that is common in older ASCII-style text.
" Java ".trim(); // "Java"strip() also removes leading and trailing whitespace, but it follows modern Unicode whitespace rules.
" Java ".strip(); // "Java"For most beginner console programs, both appear to do the same thing. Prefer strip() when working with modern Java and international text.
toLowerCase() and toUpperCase()
toLowerCase() returns a lowercase version of the string. toUpperCase() returns an uppercase version.
"Java".toLowerCase(); // "java"
"Java".toUpperCase(); // "JAVA"These methods are often used before comparison:
String command = input.nextLine().strip().toLowerCase();
if (command.equals("quit")) {
System.out.println("Bye");
}replace(old, new)
replace(old, new) returns a new string where every matching part is replaced.
"a-b-c".replace("-", "_"); // "a_b_c"
"banana".replace("na", "NA"); // "baNANA"For literal text replacement, use replace. Java also has replaceAll, which uses regular expressions, but that belongs to a later topic.
split(regex)
split(regex) cuts a string into an array of strings.
String line = "java,arrays,strings";
String[] parts = line.split(",");
System.out.println(parts[0]); // java
System.out.println(parts[1]); // arrays
System.out.println(parts[2]); // stringsThe parameter is a regular expression. A comma is simple, but characters like . and | have special meanings in regex, so they require extra care.
String.join(separator, parts)
String.join(separator, parts) does the opposite: it joins many strings into one.
String[] words = {"java", "arrays", "strings"};
String label = String.join(" / ", words);
System.out.println(label); // java / arrays / stringssplit and join are useful for CSV-style lines, tags, search keywords, and small text-cleaning tasks.