1

I'm somewhat new to programming, so sorry if this is stupid..

I have a Queue of strings, and I want to turn into a single, space-delimited string.

For example {"a","b","c"} should become "a b c"

How would I go about doing this? (I google searched this and didn't find much :/)

bjhaid
  • 9,592
  • 2
  • 37
  • 47
AmazingVal
  • 301
  • 4
  • 11

5 Answers5

2

I'd use the join method of the Apache StringUtils class (http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html).

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
2

I'm not sure what you mean by "Queue", but I'll assume it is an array and base my answer off of that assumption.

In order to combine them, try doing this.

String[] myStringArray = new String[]{"a", "b", "c"};
String myNewString = "";
for (int i = 0; i < myStringArray.length; i++) {
    if (i != 0) {
        myNewString += " " + myStringArray[i];
    } else {
        myNewString += myStringArray[i];
    }
}

Now, the value of myNewString is equal to "a b c"

EDIT:

In order to not use an if each loop, use this instead:

String[] myStringArray = new String[]{"a", "b", "c"};
String myNewString = myStringArray[0];
for (int i = 1; i < myStringArray.length; i++) {
    myNewString += " " + myStringArray[i];
}
Adam
  • 2,532
  • 1
  • 24
  • 34
0

you can also use basic logic as below:

StringBuilder builder = new StringBuilder();
for(String inStr : arrInData) {
    builder.append(inStr+" ");
}
return builder.toString();
Dark Knight
  • 8,218
  • 4
  • 39
  • 58
0

This code might not work, I did not test it, but you should understand the logic.

//This string is your queue
String[] strings = new String[];

//This is your finished String
String string = "";

for(int i = 0; i < strings.length; i++) {
    string = string + " " + strings[i];
}
Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
Ferdz
  • 1,182
  • 1
  • 13
  • 31
0
String[] strings = { "a", "b", "c" };
String result = "";
for (int i = 0; i < strings.length; i++) {
  result += strings[i] + ((i < strings.length - 1) ? " " : "");
}

The result is "a b c".

Drogba
  • 4,186
  • 4
  • 23
  • 31