Home › Learn › Java › Strings and text

String methods

Lesson 21 of 40. Split, search, cut, and replace text.

Strings cannot be changed, so every method returns a new string. The ones you will use daily: trim() removes whitespace from both ends, toLowerCase() and toUpperCase(), contains(sub), startsWith(prefix) and endsWith(suffix), indexOf(sub) (the position, or -1), substring(from, to) (from inclusive, to exclusive; substring(from) to the end), replace(old, new), and split(" ") which breaks text into a String[] at each separator.

Chaining is normal: title.trim().toLowerCase(). Split on a single space leaves empty pieces when spaces double up; split("\\s+") splits on any run of whitespace, and an all-whitespace string splits into one empty piece, which is why word counters trim first and treat empty text as zero words.

String line = "  name: Ada  ";
String[] parts = line.trim().split(": ");
System.out.println(parts[0] + "|" + parts[1]);   // name|Ada
System.out.println("hello".substring(1, 3));      // el

Your task

Write static String initials(String fullName) returning the first character of each space-separated word in upper case ("ada byron lovelace" gives "ABL"), static String maskEmail(String email) keeping the first character and everything from the @ onward and replacing the rest with *** ("ada@example.com" gives "a***@example.com"), and static int countWords(String text) returning the number of words separated by whitespace (0 for blank text).

Hint 1

initials: for (String w : fullName.split(" ")) result += Character.toUpperCase(w.charAt(0)); or use w.substring(0, 1).toUpperCase().

Hint 2

maskEmail: int at = email.indexOf("@"); return email.substring(0, 1) + "***" + email.substring(at); countWords: trim first, return 0 when empty, else split("\\s+").length.

Show the solution
public class Main {
    static String initials(String fullName) {
        String result = "";
        for (String word : fullName.split(" ")) {
            result += word.substring(0, 1).toUpperCase();
        }
        return result;
    }

    static String maskEmail(String email) {
        int at = email.indexOf("@");
        return email.substring(0, 1) + "***" + email.substring(at);
    }

    static int countWords(String text) {
        String trimmed = text.trim();
        if (trimmed.isEmpty()) {
            return 0;
        }
        return trimmed.split("\\s+").length;
    }

    public static void main(String[] args) {
        System.out.println(initials("ada byron lovelace") + " " + maskEmail("ada@example.com") + " " + countWords("one two  three"));
    }
}

    Compiles with OpenJDK javac and TeaVM, both compiled to WebAssembly (7 MB download the first time, then cached), and runs in this tab; nothing is sent anywhere.