Split and Join a String in Java



Splitting and join a string

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

Example

A class named 'Demo' contains the main function. Here a String object is defined and split based on the '_' value up to 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, and the output is displayed.

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

Following is the output of the above program ?

The split string is:
This
is
a
sample
The joined string is:
This is a sample
Updated on: 2024-12-17T23:02:34+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements