Monday, July 1, 2019

java - Queue of strings to single string





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 :/)


Answer



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


No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...