Java:像 PHP 的 join() 这样的数组函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1515437/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: function for arrays like PHP's join()?
提问by Nick Heiner
I want to join a String[]
with a glue string. Is there a function for this?
我想String[]
用胶水串连接 a 。有这个功能吗?
采纳答案by coobird
Starting from Java8it is possible to use String.join()
.
从Java8开始,可以使用String.join()
.
String.join(", ", new String[]{"Hello", "World", "!"})
Generates:
产生:
Hello, World, !
Otherwise, Apache Commons Langhas a StringUtils
class which has a join
function which will join arrays together to make a String
.
否则,Apache Commons Lang有一个StringUtils
类,该类具有join
将数组连接在一起以生成String
.
For example:
例如:
StringUtils.join(new String[] {"Hello", "World", "!"}, ", ")
Generates the following String
:
生成以下内容String
:
Hello, World, !
回答by coobird
Not in core, no. A search for "java array join string glue" will give you some code snippets on how to achieve this though.
不在核心,不。搜索“java array join string paste”将为您提供一些关于如何实现这一点的代码片段。
e.g.
例如
public static String join(Collection s, String delimiter) {
StringBuffer buffer = new StringBuffer();
Iterator iter = s.iterator();
while (iter.hasNext()) {
buffer.append(iter.next());
if (iter.hasNext()) {
buffer.append(delimiter);
}
}
return buffer.toString();
}
回答by JonMR
Nothing built-in that I know of.
我所知道的没有内置的东西。
Apache Commons Langhas a class called StringUtils
which contains many join functions.
Apache Commons Lang有一个名为的类StringUtils
,其中包含许多连接函数。
回答by Jay
You could easily write such a function in about ten lines of code:
你可以很容易地用大约十行代码编写这样一个函数:
String combine(String[] s, String glue)
{
int k = s.length;
if ( k == 0 )
{
return null;
}
StringBuilder out = new StringBuilder();
out.append( s[0] );
for ( int x=1; x < k; ++x )
{
out.append(glue).append(s[x]);
}
return out.toString();
}
回答by Adriaan Koster
java.util.Arrays has an 'asList' method. Together with the java.util.List/ArrayList API this gives you all you need:;
java.util.Arrays 有一个“asList”方法。与 java.util.List/ArrayList API 一起为您提供所需的一切:;
private static String[] join(String[] array1, String[] array2) {
List<String> list = new ArrayList<String>(Arrays.asList(array1));
list.addAll(Arrays.asList(array2));
return list.toArray(new String[0]);
}
回答by Richard Corfield
This is how I do it.
我就是这样做的。
private String join(String[] input, String delimiter)
{
StringBuilder sb = new StringBuilder();
for(String value : input)
{
sb.append(value);
sb.append(delimiter);
}
int length = sb.length();
if(length > 0)
{
// Remove the extra delimiter
sb.setLength(length - delimiter.length());
}
return sb.toString();
}
回答by Rob at TVSeries.com
Given:
鉴于:
String[] a = new String[] { "Hello", "World", "!" };
Then as an alternative to coobird's answer, where the glue is ", ":
然后作为 coobird 答案的替代,其中胶水是“,”:
Arrays.asList(a).toString().replaceAll("^\[|\]$", "")
Or to concatenate with a different string, such as " & ".
或者连接不同的字符串,例如“ & ”。
Arrays.asList(a).toString().replaceAll(", ", " & ").replaceAll("^\[|\]$", "")
However... this one ONLY works if you know that the values in the array or list DO NOT contain the character string ", ".
但是……只有当您知道数组或列表中的值不包含字符串“,”时,此方法才有效。
回答by everlasto
A little mod instead of using substring():
一个小的 mod 而不是使用 substring():
//join(String array,delimiter)
public static String join(String r[],String d)
{
if (r.length == 0) return "";
StringBuilder sb = new StringBuilder();
int i;
for(i=0;i<r.length-1;i++){
sb.append(r[i]);
sb.append(d);
}
sb.append(r[i]);
return sb.toString();
}
回答by bertie
Google guava's library also has this kind of capability. You can see the String[] example also from the API.
Google guava 的库也有这种能力。您也可以从 API 中看到 String[] 示例。
As already described in the api, beware of the immutability of the builder methods.
正如 api 中已经描述的那样,要注意构建器方法的不变性。
It can accept an array of objects so it'll work in your case. In my previous experience, i tried joining a Stack which is an iterable and it works fine.
它可以接受一组对象,因此它适用于您的情况。在我之前的经验中,我尝试加入一个可迭代的 Stack,它工作正常。
Sample from me :
我的样品:
Deque<String> nameStack = new ArrayDeque<>();
nameStack.push("a coder");
nameStack.push("i am");
System.out.println("|" + Joiner.on(' ').skipNulls().join(nameStack) + "|");
prints out : |i am a coder|
打印出来: |i am a coder|
回答by devstopfix
If you are using the Spring Frameworkthen you have the StringUtilsclass:
如果您使用的是Spring Framework,那么您将拥有StringUtils类:
import static org.springframework.util.StringUtils.arrayToDelimitedString;
arrayToDelimitedString(new String[] {"A", "B", "C"}, "\n");