Menu
CoddyTech

Iterating Over Strings Part 2

Part of the Fundamentals section of Coddy's GDScript journey. Lesson 72 of 92.

The split() method cuts a string at every occurrence of a separator and returns the pieces as an array:

var data := "john,25,new york"
var parts := data.split(",")
print(parts)
["john", "25", "new york"]

The result is a PackedStringArray, a compact array that holds only strings. You index it, loop over it and print it like any array: parts[1] is "25".

When the separator appears several times in a row, split() returns empty strings between them. Pass false as a second argument to leave the empty pieces out:

print("I   love   coding".split(" "))
print("I   love   coding".split(" ", false))
["I", "", "", "love", "", "", "coding"]
["I", "love", "coding"]

The join() method does the opposite: it is called on the separator string and combines the elements of an array of strings into one string:

var words := ["Hello", "World", "Godot"]
print(" ".join(words))
print(",".join(words))
Hello World Godot
Hello,World,Godot
challenge icon

Challenge

Easy

The program reads two lines: a text and a separator.

  1. Split text into words at the spaces. Words can be separated by several spaces, and there can be spaces at the start or the end: leave the empty pieces out.
  2. Join the words with separator and print the result.

For the inputs Hello world godot and -, the output is:

Hello-world-godot

Try it yourself

extends Node

func _ready():
	var text := OS.read_string_from_stdin()
	var separator := OS.read_string_from_stdin()
	# Write your code below
quiz iconTest yourself

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

All lessons in Fundamentals

Practice on your own: Online GDScript compiler