简体   繁体   English

将字符串数组转换为Java中的字符串

[英]Convert array of strings into a string in Java

我想要将字符串数组转换为字符串的 Java 代码。

Java 8+ Java 8+

Use String.join() :使用String.join()

String str = String.join(",", arr);

Note that arr can also be any Iterable (such as a list), not just an array.请注意, arr也可以是任何可Iterable (例如列表),而不仅仅是数组。

If you have a Stream , you can use the joining collector:如果您有Stream ,则可以使用加入收集器:

Stream.of("a", "b", "c")
      .collect(Collectors.joining(","))

Legacy (Java 7 and earlier)旧版(Java 7 及更早版本)

StringBuilder builder = new StringBuilder();
for(String s : arr) {
    builder.append(s);
}
String str = builder.toString();

Alternatively, if you just want a "debug-style" dump of an array:或者,如果您只想要数组的“调试式”转储:

String str = Arrays.toString(arr);

Note that if you're really legacy (Java 1.4 and earlier) you'll need to replace StringBuilder there with StringBuffer .请注意,如果您真的是旧版(Java 1.4 及更早版本),则需要将StringBuilder替换为StringBuffer

Android安卓

Use TextUtils.join() :使用TextUtils.join()

String str = TextUtils.join(",", arr);

General notes一般注意事项

You can modify all the above examples depending on what characters, if any, you want in between strings.您可以根据字符串之间想要的字符(如果有)来修改上述所有示例。

DON'T use a string and just append to it with += in a loop like some of the answers show here.不要使用字符串,只需在循环中使用 += 附加到它,就像此处显示的某些答案一样。 This sends the GC through the roof because you're creating and throwing away as many string objects as you have items in your array.这将 GC 发送到屋顶,因为您正在创建和丢弃与数组中的项目一样多的字符串对象。 For small arrays you might not really notice the difference, but for large ones it can be orders of magnitude slower.对于小数组,您可能不会真正注意到差异,但对于大数组,它可能会慢几个数量级。

Use Apache commons StringUtils.join() .使用 Apache 公共StringUtils.join() It takes an array, as a parameter (and also has overloads for Iterable and Iterator parameters) and calls toString() on each element (if it is not null) to get each elements string representation.它接受一个数组作为参数(并且还有IterableIterator参数的重载)并在每个元素上调用toString() (如果它不为 null)来获取每个元素的字符串表示。 Each elements string representation is then joined into one string with a separator in between if one is specified:如果指定了一个分隔符,则每个元素字符串表示然后连接成一个字符串,中间有一个分隔符:

String joinedString = StringUtils.join(new Object[]{"a", "b", 1}, "-");
System.out.println(joinedString);

Produces:产生:

a-b-1

I like using Google's Guava Joiner for this, eg:我喜欢为此使用Google 的 Guava Joiner ,例如:

Joiner.on(", ").skipNulls().join("Harry", null, "Ron", "Hermione");

would produce the same String as:将产生与以下相同的字符串:

new String("Harry, Ron, Hermione");

ETA: Java 8 has similar support now: ETA:Java 8 现在有类似的支持:

String.join(", ", "Harry", "Ron", "Hermione");

Can't see support for skipping null values, but that's easily worked around.看不到对跳过空值的支持,但这很容易解决。

From Java 8, the simplest way I think is:从 Java 8 开始,我认为最简单的方法是:

    String[] array = { "cat", "mouse" };
    String delimiter = "";
    String result = String.join(delimiter, array);

This way you can choose an arbitrary delimiter.这样您就可以选择任意分隔符。

You could do this, given an array a of primitive type:你可以这样做,给定一个原始类型的数组a

StringBuffer result = new StringBuffer();
for (int i = 0; i < a.length; i++) {
   result.append( a[i] );
   //result.append( optional separator );
}
String mynewstring = result.toString();

Try the Arrays.deepToString method.尝试Arrays.deepToString方法。

Returns a string representation of the "deep contents" of the specified array.返回指定数组的“深层内容”的字符串表示形式。 If the array contains other arrays as elements, the string representation contains their contents and so on.如果数组包含其他数组作为元素,则字符串表示包含它们的内容等等。 This method is designed for converting multidimensional arrays to strings此方法旨在将多维数组转换为字符串

Try the Arrays.toString overloaded methods.尝试Arrays.toString重载方法。

Or else, try this below generic implementation:或者,试试下面的通用实现:

public static void main(String... args) throws Exception {

    String[] array = {"ABC", "XYZ", "PQR"};

    System.out.println(new Test().join(array, ", "));
}

public <T> String join(T[] array, String cement) {
    StringBuilder builder = new StringBuilder();

    if(array == null || array.length == 0) {
        return null;
    }

    for (T t : array) {
        builder.append(t).append(cement);
    }

    builder.delete(builder.length() - cement.length(), builder.length());

    return builder.toString();
}

Following is an example of Array to String conversion.以下是数组到字符串转换的示例。

public class ArrayToString
    {
public static void main(String[] args) { String[] strArray = new String[]{"Java", "PHP", ".NET", "PERL", "C", "COBOL"};

        String newString = Arrays.toString(strArray);

        newString = newString.substring(1, newString.length()-1);

        System.out.println("New New String: " + newString);
    }
}

String[] strings = new String[25000];
for (int i = 0; i < 25000; i++) strings[i] = '1234567';

String result;
result = "";
for (String s : strings) result += s;
//linear +: 5s

result = "";
for (String s : strings) result = result.concat(s);
//linear .concat: 2.5s

result = String.join("", strings);
//Java 8 .join: 3ms

Public String join(String delimiter, String[] s)
{
    int ls = s.length;
    switch (ls)
    {
        case 0: return "";
        case 1: return s[0];
        case 2: return s[0].concat(delimiter).concat(s[1]);
        default:
            int l1 = ls / 2;
            String[] s1 = Arrays.copyOfRange(s, 0, l1); 
            String[] s2 = Arrays.copyOfRange(s, l1, ls); 
            return join(delimiter, s1).concat(delimiter).concat(join(delimiter, s2));
    }
}
result = join("", strings);
// Divide&Conquer join: 7ms

If you don't have the choise but to use Java 6 or 7 then you should use Divide&Conquer join.如果您没有选择但要使用 Java 6 或 7,那么您应该使用 Divide&Conquer join。

Use Apache Commons' StringUtils library 's join method.使用 Apache Commons 的StringUtils 库的 join 方法。

String[] stringArray = {"a","b","c"};
StringUtils.join(stringArray, ",");

You want code which produce string from arrayList,您想要从 arrayList 生成字符串的代码,

Iterate through all elements in list and add it to your String result

you can do this in 2 ways: using String as result or StringBuffer/StringBuilder.您可以通过两种方式执行此操作:使用 String 作为结果或 StringBuffer/StringBuilder。

Example:例子:

String result = "";
for (String s : list) {
    result += s;
}

...but this isn't good practice because of performance reason. ...但由于性能原因,这不是一个好习惯。 Better is using StringBuffer (threads safe) or StringBuilder which are more appropriate to adding Strings最好使用StringBuffer (线程安全)或StringBuilder ,它们更适合添加字符串

When we use stream we do have more flexibility, like当我们使用流时,我们确实有更多的灵活性,比如
map --> convert any array object to toString映射 --> 将任何数组对象转换为 toString
filter --> remove when it is empty过滤器 --> 为空时删除
join --> Adding joining character join --> 添加加入字符

    //Deduplicate the comma character in the input string
    String[] splits = input.split("\\s*,\\s*");
    return Arrays.stream(splits).filter(StringUtils::isNotBlank).collect(Collectors.joining(", "));
String array[]={"one","two"};
String s="";

for(int i=0;i<array.length;i++)
{
  s=s+array[i];
}

System.out.print(s);

如果你知道数组有多少元素,一个简单的方法是这样做:

String appendedString = "" + array[0] + "" + array[1] + "" + array[2] + "" + array[3]; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM