Iterating Over Strings Part 1
Part of the Fundamentals section of Coddy's GDScript journey. Lesson 71 of 92.
A string is a sequence of characters, so a for loop can go through it like an array. Each character is a string of length 1:
var text := "Hey"
for letter in text:
print(letter)H
e
yStrings have indexes too, starting at 0. text.length() is the number of characters, so range(text.length()) gives every index:
for i in range(text.length()):
print("position %d: %s" % [i, text[i]])position 0: H
position 1: e
position 2: yTo compare letters without caring about case, convert them first: to_lower() returns the string in lowercase and to_upper() in uppercase. "PiZZa".to_lower() is "pizza".
Challenge
EasyThe program reads one line of text into text. Print how many times the letter p appears in it, counting both p and P.
For the input Happy people play ping pong, the output is 7.
Try it yourself
extends Node
func _ready():
var text := OS.read_string_from_stdin()
# Count p and P in text, then print the count
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