Split & Join Strings

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

BeginnerTopic: Module 4: String Programs
Back

Java Split & Join Strings Program

This program helps you to learn the fundamental structure and syntax of Java programming.

Try This Code
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

Understanding Split & Join Strings

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

Note: To write and run Java programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Java Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Java programs.

Table of Contents