Menu
CoddyTech

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
y

Strings 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: y

To 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 icon

Challenge

Easy

The 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
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