Monday 1 July 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...