+5 votes

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.

in Engine by (233 points)

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

4 Answers

+1 vote

I would use for loop

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

for i in range(0,strings.size()):
    complete += strings[i]
by (111 points)
+2 votes
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
by (84 points)
+15 votes

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
by (152 points)
edited by
0 votes

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
by (1,656 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.