×

Java Programs

Java Practice

Java program to construct a string with substrings separated by a delimiter

Java example to construct a string with substrings separated by a delimiter.
Submitted by Nidhi, on June 09, 2022

Problem statement

In this program, we will use StringJoiner class to create a string. Here, we will add substrings that are separated by a specified delimiter.

Java program to construct a string with substrings separated by a delimiter

The source code to construct a string with substrings separated by a delimiter is given below. The given program is compiled and executed successfully.

// Java program to construct a string with substrings 
// separated by a delimiter

import java.util.*;

public class Main {
  public static void main(String[] args) {
    StringJoiner str = new StringJoiner(",");

    str.add("ABC");
    str.add("LMN");
    str.add("PQR");
    str.add("XYZ");

    System.out.println("Constructed String is: '" + str + "'");
  }
}

Output

Constructed String is: 'ABC,LMN,PQR,XYZ'

Explanation

In the above program, we imported the "java.util.*" package to use the StringJoiner class. Here, we created a public class Main.

The Main class contains a main() method. The main() method is the entry point for the program. And, created an object of StringJoiner class to construct a string with the specified delimiter ",". Then we added substrings using add() method. After that, we printed the constructed string.

Java StringJoiner Class Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.