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,GodotChallenge
EasyThe program reads two lines: a text and a separator.
- Split
textinto 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. - Join the words with
separatorand print the result.
For the inputs Hello world godot and -, the output is:
Hello-world-godotTry it yourself
extends Node
func _ready():
var text := OS.read_string_from_stdin()
var separator := OS.read_string_from_stdin()
# Write your code below
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsInteger DivisionModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators10Functions
Declare a FunctionArgumentsReturnReturn TypesRecap - Sigma FunctionRecap - Validation FunctionDefault Values13Iterating Over Arrays
Iterating Over ElementsIterating With IndexesIterating Over Strings Part 1Iterating Over Strings Part 25Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary OperatorPractice on your own: Online GDScript compiler