Split & Join Strings in Java
Split a sentence into words and then join them with a different delimiter.
BeginnerModule 4: String ProgramsExample 23 of 25
split-join-strings.java
1import java.util.Scanner;2import java.util.StringJoiner;34public class Main {5 public static void main(String[] args) {6 Scanner sc = new Scanner(System.in);7 System.out.print("Enter a sentence: ");8 String s = sc.nextLine();910 String[] words = s.trim().split("\\s+");11 StringJoiner joiner = new StringJoiner("-");12 for (String w : words) {13 joiner.add(w);14 }15 System.out.println("Joined: " + joiner.toString());16 sc.close();17 }18}
Output
Enter a sentence: Java is fun Joined: Java-is-fun
What's going on
We split on spaces and re-join using StringJoiner with '-' delimiter.