Elegant way to create string from array items

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By brunosxs
:warning: Old Version Published before Godot 3 was released.

Hello guys. I have a problem that has been bugging me. Supose I have the following:

var strings = ["Hello ", "there!", " How'dy?"]

I’ve been trying to find a good way to create a String from this variable in an elegant manner.
The only way I was able to, involved me using var complete = String(strings)but this in turn generated a written representation of the array, with the brackets and commas.

Its a little perplexing that theres a function to do this in one direction (String.rsplit) but not in the other direction.

shayneoneill | 2020-06-26 17:40

:bust_in_silhouette: Reply From: Maksanty

I would use for loop

var strings = ["Hello ", "there!", " How'dy?"]
var complete = ""

for i in range(0,strings.size()):
    complete += strings[i]
:bust_in_silhouette: Reply From: Kermer
func _ready():
	var myArray = ["this","is","some","array"]
	print(arr_join(myArray,", "))

func arr_join(arr, separator = ""):
	var output = "";
	for s in arr:
		output += str(s) + separator
	output = output.left( output.length() - separator.length() )
	return output
:bust_in_silhouette: Reply From: flesk

This is possible in Godot 3:

var joined_string = PoolStringArray(strings).join("")

I don’t think it’s possible to achieve with a one-liner in Godot 2, however.

That is, unless you know exactly how many elements your array contains, because then you can just use string formatting:

var joined_string = "%s%s%s" % strings
:bust_in_silhouette: Reply From: Eric Ellingson

For anyone that finds this and also wants to be able to join the items using an additional string as the “glue” (like a comma, for example), this works well:

func array_join(arr : Array, glue : String = '') -> String:
    var string : String = ''
    for index in range(0, arr.size()):
        string += str(arr[index])
        if index < arr.size() - 1:
            string += glue
    return string

if you’re using godot version < 3.1:

func array_join(arr, glue = ''):
    var string = ''
    for index in range(0, arr.size()):
        string += str(arr[index])
        if index < arr.size() - 1:
            string += glue
    return string