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)returnstrueif the text appears anywhere, likeinbegins_with(text)andends_with(text)check only the start or the endfind(text)returns the index where the text first appears, or-1if it does not appearrfind(text)returns the index of the last appearancecount(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
3find() 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
14These 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
EasyThe 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,.orgor.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:
validTry it yourself
extends Node
func _ready():
var email := OS.read_string_from_stdin()
# Print valid or invalid
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