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
EasyThe 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:
- The number of words
- The words without the spaces around them, in uppercase, joined with
>(space, greater-than sign, space) - 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
greenTry it yourself
extends Node
func _ready():
var line := OS.read_string_from_stdin()
# Print the count, the joined words and the longest word
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String MethodsSearching in StringsReplace and TrimSplit and JoinRecap - Username Check4Dictionaries Part 2
Nested DictionariesArrays of DictionariesMerging DictionariesCopying DictionariesRecap - Frequency Counter2Advanced Decision Making
Match With VariablesMatch GuardsArray PatternsDictionary PatternsMembership ChecksRecap - Command Parser5Contact Book Application
Display MenuAdd Contact8Student Records Manager
Project OverviewAdd Student3Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysJagged ArraysCommon 2D Array PatternsRecap - Game Board6Sets with Dictionaries
What is a Set?Dictionary as a SetAdding and RemovingUnion and IntersectionSet DifferenceRecap - Remove Duplicates9Advanced Data Aggregation
Summing ValuesFinding Minimum and MaximumCustom SortingRecap - Dictionary SorterPractice on your own: Online GDScript compiler