Menu
CoddyTech

Searching in Strings

Part of the Logic & Flow section of Coddy's GDScript journey. Lesson 2 of 78.

The in operator tells you whether a text appears in a string. When you need more than yes or no, strings have search methods:

  • contains(text) returns true if the text appears anywhere, like in
  • begins_with(text) and ends_with(text) check only the start or the end
  • find(text) returns the index where the text first appears, or -1 if it does not appear
  • rfind(text) returns the index of the last appearance
  • count(text) returns how many times the text appears
var email := "alice@coddy.tech"
print(email.begins_with("alice"))
print(email.ends_with(".tech"))
print(email.find("@"))
print(email.find("x"))
print(email.count("c"))
true
true
5
-1
3

find() takes an optional second argument: the index where the search starts. Use it to find the next appearance after one you already found:

var text := "one fish, two fish"
var first := text.find("fish")
print(first)
print(text.find("fish", first + 1))
4
14

These methods are case-sensitive: "Hello".contains("hello") is false. Convert the string with to_lower() first, or use the versions that ignore case: findn(), containsn() and countn().

challenge icon

Challenge

Easy

The program reads an email address into email. Check that it passes all of these rules:

  • It contains exactly one @
  • It does not begin with @
  • It contains no spaces
  • It ends with .com, .org or .tech, in any mix of uppercase and lowercase

Print valid when every rule passes, otherwise invalid. For the input alice@CODDY.TECH, the output is:

valid

Try it yourself

extends Node

func _ready():
	var email := OS.read_string_from_stdin()
	# Print valid or invalid
quiz iconTest yourself

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

All lessons in Logic & Flow

Practice on your own: Online GDScript compiler