问题描述
我是 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.
我在谷歌上搜索了相同的内容,但对结果不满意.任何人对我的问题有好的解决方案将不胜感激.
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 for String 揭示了 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();
这篇关于Java 等价于 Explode 和 Implode(PHP)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!