0

For example, If I have an array

String[] myStringArray = new String[]{"x", "a", "r", "y"};

How do I make a singular string that is "xary"

user2336315
  • 15,697
  • 10
  • 46
  • 64
NothingHere
  • 11
  • 1
  • 3

3 Answers3

1

You can iterate through all the elements of you array and append them in a StringBuilder. Get the resulting String calling toString().

With java 8, you could get a Stream from the array and use the reduce operation.

String s = Arrays.stream(myStringArray).reduce("", String::concat); //xary

The above java 8 solution has a worse complexity than using joining, so don't do that ! :)

user2336315
  • 15,697
  • 10
  • 46
  • 64
1

You can manually concatenate it with a simple for loop like so

String myString;
for(int i = 0; i < myStringArray.length;i++)
myString + = myStringArray[i];

LeatherFace
  • 478
  • 2
  • 11
  • Yes, you could do that, but don't. If you want to do it with a loop then use a foreach-style loop as @Mudit suggests, and use a `StringBuilder` to assemble the result instead of the `String` concatenation operator. – John Bollinger Oct 29 '14 at 21:07
0
String[] myStringArray = new String[]{"x", "a", "r", "y"};
StringBuilder builder = new StringBuilder();
for(String s:myStringArray)
    builder.append(s);

System.out.println(builder );
Mudit Shukla
  • 814
  • 2
  • 6
  • 16