Java program to split and join a string


To split and join a string in Java, use the split() and join() method as in the below example −

Example

public class Demo{
   public static void main(String args[]){
      String my_str = "This_is_a_sample";
      String[] split_str = my_str.split("_", 4);
      System.out.println("The split string is:");
      for (String every_Str : split_str)
      System.out.println(every_Str);
      String joined_str = String.join("_", "This", "is", "a", "sample");
      System.out.println("The joined string is:");
      System.out.println(joined_str);
   }
}

Output

The split string is:
This
is
a
sample
The joined string is:
This_is_a_sample

A class named Demo contains the main function. Here a String object is defined and it is split based on the ‘_’ value upto the last word. A ‘for’ loop is iterated over and the string is split based on the ‘_’ value. Again, the string is joined using the ‘join’ function. Relevant messages are displayed on the console.

Updated on: 07-Jul-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements