Split & Join Strings

Split a sentence into words and then join them with a different delimiter.

JavaBeginner
Java
import java.util.Scanner;
import java.util.StringJoiner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a sentence: ");
        String s = sc.nextLine();

        String[] words = s.trim().split("\\s+");
        StringJoiner joiner = new StringJoiner("-");
        for (String w : words) {
            joiner.add(w);
        }
        System.out.println("Joined: " + joiner.toString());
        sc.close();
    }
}

Output

Enter a sentence: Java is fun
Joined: Java-is-fun

We split on spaces and re-join using StringJoiner with '-' delimiter.