Working With Words

Splitting a line into words

line.trim().split("\\s+") cuts a line at every run of spaces and gives an array of words:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String line = sc.nextLine();
        String[] words = line.trim().split("\\s+");
        System.out.println(words.length + " words");
        String longest = "";
        for (String w : words) {
            if (w.length() > longest.length()) longest = w;
        }
        System.out.println("longest: " + longest);
    }
}

Input (what the user types)

  data   structures are fun  

Output

4 words
longest: structures

Reverse with two indexes

To reverse something in place, put one finger at each end, swap, and walk inward until the fingers meet. A String can't change, so turn it into a char[] first:

public class Main {
    static String reverse(String s) {
        char[] c = s.toCharArray();
        int left = 0, right = c.length - 1;
        while (left < right) {
            char tmp = c[left];
            c[left] = c[right];
            c[right] = tmp;
            left++;
            right--;
        }
        return new String(c);
    }

    public static void main(String[] args) {
        System.out.println(reverse("stressed"));
        System.out.println(reverse("level"));
    }
}

Output

desserts
level

You'll meet this two-pointer idea many more times in Module 5.

Remember: Need to change characters? Use char[] or StringBuilder. Need to build a long answer? Use StringBuilder. Never += in a big loop.

HOME LABS COMMUNITY DASHBOARD