Java 等同于“爆炸与内爆”(PHP)

我是新在 Java 虽然有一个良好的经验在 PHP,并寻找完美的替代爆炸和内爆(可在 PHP)函数在 Java。

我在谷歌上搜索了同样的结果,但对结果并不满意。 任何对我的问题有好的解决方案的人都会受到感激。

例如:

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));

预期输出:

[x, y, z]
143679 次浏览

if you are talking about in the reference of String Class. so you can use

subString/split

for Explode & use String

concate

for Implode.

String.split() can provide you with a replacement for explode()

For a replacement of implode() I'd advice you to write either a custom function or use Apache Commons's StringUtils.join() functions.

java.lang.String.split(String regex) is what you are looking for.

Good alternatives are the String.split and StringUtils.join methods.

Explode :

String[] exploded="Hello World".split(" ");

Implode :

String imploded=StringUtils.join(new String[] {"Hello", "World"}, " ");

Keep in mind though that StringUtils is in an external library.

I'm not familiar with PHP, but I think String.split is Java equivalent to PHP explode. As for implode, standart library does not provide such functionality. You just iterate over your array and build string using StringBuilder/StringBuffer. Or you can try excellent Google Guava Splitter and Joiner or split/join methods from Apache Commons implode0.

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();