相当于Explode and Implode(PHP)的Java [英] Java equivalent to Explode and Implode(PHP)
问题描述
我是Java的新手,尽管在PHP方面有丰富的经验,并且正在寻找Java的爆炸和内爆(PHP中可用)函数的完美替代品.
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.
我已经用Google搜索了相同的结果,但对结果不满意. 任何对我的问题有好的解决方案的人都将不胜感激.
I have Googled for the same but not satisfied with the results. Anyone has the good solution for my problem will be appreciated.
例如:
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]
推荐答案
用于字符串的Javadoc 揭示了String.split()
是您要查找的有关explode
的内容.
The Javadoc for String reveals that String.split()
is what you're looking for in regard to explode
.
Java不包括等效的连接"的内爆".您可能只想编写几行代码,而不是像其他答案所建议的那样为简单的函数包括巨大的外部依赖关系.有多种方法可以完成该任务.使用StringBuilder
是一个:
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();
这篇关于相当于Explode and Implode(PHP)的Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!