Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java equivalent to Explode and Implode(PHP) [closed]

I am new in Java although had a good experience in PHP, and looking for perfect replacement for explode and implode (available in PHP) functions in Java.

I have Googled for the same but not satisfied with the results. Anyone has the good solution for my problem will be appreciated.

For example:

String s = "x,y,z"; //Here I need a function to divide the string into an array based on a character. array a = javaExplode(',', s);  //What is javaExplode? System.out.println(Arrays.toString(a)); 

Desired output:

[x, y, z] 
like image 272
Pankaj Wanjari Avatar asked May 27 '13 12:05

Pankaj Wanjari


People also ask

What is difference between explode () or implode () in PHP?

PHP Explode function breaks a string into an array. PHP Implode function returns a string from an array.

Why explode () is used?

The explode function is utilized to "Split a string into pieces of elements to form an array". The explode function in PHP enables us to break a string into smaller content with a break. This break is known as the delimiter.

What would implode explode string )) do?

PHP implode() and explode() The implode() function takes an array, joins it with the given string, and returns the joined string. The explode() function takes a string, splits it by specified string, and returns an array.


1 Answers

The Javadoc for String reveals that String.split() is what you're looking for in regard to explode.

Java does not include a "implode" of "join" equivalent. Rather than including a giant external dependency for a simple function as the other answers suggest, you may just want to write a couple lines of code. There's a number of ways to accomplish that; using a StringBuilder is one:

String foo = "This,that,other"; String[] split = foo.split(","); StringBuilder sb = new StringBuilder(); for (int i = 0; i < split.length; i++) {     sb.append(split[i]);     if (i != split.length - 1) {         sb.append(" ");     } } String joined = sb.toString(); 
like image 111
Brian Roach Avatar answered Sep 28 '22 07:09

Brian Roach