Menu
CoddyTech

Split and Join

Part of the Logic & Flow section of Coddy's GDScript journey. Lesson 4 of 78.

You already cut strings with split() and glued arrays with join(). Both can do more.

The pieces of split() are strings, exactly as they appear between the separators, spaces included. Clean or convert each piece before you use it. An element of the result can be replaced through its index:

var items := "sword, shield ,bow".split(",")
print(items)
for i in range(items.size()):
	items[i] = items[i].strip_edges()
print(items)
["sword", " shield ", "bow"]
["sword", "shield", "bow"]

The second argument of split() is the one you met before: true keeps empty pieces, false drops them. A third argument limits the number of cuts. split(" ", true, 1) cuts only at the first space, which separates a command from the rest of the line:

print("say hello there".split(" ", true, 1))
["say", "hello there"]

rsplit() works the same way but counts the cuts from the right, so it can cut at the last dot of a file name:

print("save.backup.json".rsplit(".", true, 1))
["save.backup", "json"]

join() also accepts an array of numbers and converts each one to text: ", ".join([3, 1, 2]) is "3, 1, 2".

challenge icon

Challenge

Easy

The program reads one line of words separated by commas into line. There can be spaces around the words, for example red, green ,blue.

Print three lines:

  1. The number of words
  2. The words without the spaces around them, in uppercase, joined with > (space, greater-than sign, space)
  3. The longest word, without spaces. If several words have the same length, print the first one

For the input red, green ,blue, the output is:

3
RED > GREEN > BLUE
green

Try it yourself

extends Node

func _ready():
	var line := OS.read_string_from_stdin()
	# Print the count, the joined words and the longest word
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Online GDScript compiler