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

I want the Java code for converting an array of strings into an string.

This question is related to java arrays string

The answer is


Use Apache commons 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. 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

String array[]={"one","two"};
String s="";

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

System.out.print(s);

From Java 8, the simplest way I think is:

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

This way you can choose an arbitrary delimiter.


Try the Arrays.deepToString method.

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


If you know how much elements the array has, a simple way is doing this:

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

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


Try the Arrays.toString overloaded methods.

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

Use Apache Commons' StringUtils library's join method.

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

You could do this, given an array a of primitive type:

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

You want code which produce string from 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.

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


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.


I like using Google's Guava Joiner for this, e.g.:

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:

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

Can't see support for skipping null values, but that's easily worked around.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript