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]
PHP Explode function breaks a string into an array. PHP Implode function returns a string from an array.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With