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

Java program for splitting and concatenating strings

WBOY
Release: 2023-09-06 21:37:06
forward
994 people have browsed it

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);
   }
}
Copy after login

Output

The split string is:
This
is
a
sample
The joined string is:
This_is_a_sample
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template