Home > Java > javaTutorial > How to Concatenate Elements of a String Array in Java: Equivalent to PHP\'s join() Function?

How to Concatenate Elements of a String Array in Java: Equivalent to PHP\'s join() Function?

DDD
Release: 2024-10-29 02:53:30
Original
1031 people have browsed it

How to Concatenate Elements of a String Array in Java: Equivalent to PHP's join() Function?

Java Equivalent of PHP's Join Function for Arrays

Problem:

You need to concatenate elements of a String array using a delimiter, similar to PHP's join() function.

Solution:

Java 8 and Later:

Starting from Java 8, you can use the built-in String.join() method:

<code class="java">String.join(", ", new String[] {"Hello", "World", "!"})</code>
Copy after login

This will generate:

Hello, World, !
Copy after login
Copy after login

Java 7 and Earlier:

For earlier versions of Java, you can use the StringUtils class from Apache Commons Lang:

<code class="java">StringUtils.join(new String[] {"Hello", "World", "!"}, ", ")</code>
Copy after login

This will also generate the string:

Hello, World, !
Copy after login
Copy after login

Note: The StringUtils.join() method is more versatile and supports additional features, such as customizing the separator character and handling null elements.

The above is the detailed content of How to Concatenate Elements of a String Array in Java: Equivalent to PHP's join() Function?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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