Home  >  Article  >  Java  >  Java program for splitting and concatenating strings

Java program for splitting and concatenating strings

WBOY
WBOYforward
2023-09-06 21:37:06919browse

Java program for splitting and concatenating strings

To split and concatenate strings in Java, use split() and join() methods as shown in the example below −

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 split to the last word based on '_' value. Iterate using 'for' loop and split the string based on '_' value. Then, use the 'join' function to concatenate the strings. Relevant messages will be displayed on the console.

The above is the detailed content of Java program for splitting and concatenating strings. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete