String Functions in GDScript

extends Node

# We alias print to a shorter name as we'll use it a lot below.
var p = print

func _ready():
    # Here's a sample of the string functions available in GDScript.
    # In GDScript, these are methods on the String object itself,
    # so we call them directly on the string.
    
    p("Contains:  ", "test".find("es") != -1)
    p("Count:     ", "test".count("t"))
    p("HasPrefix: ", "test".begins_with("te"))
    p("HasSuffix: ", "test".ends_with("st"))
    p("Index:     ", "test".find("e"))
    p("Join:      ", "-".join(["a", "b"]))
    p("Repeat:    ", "a".repeat(5))
    p("Replace:   ", "foo".replace("o", "0"))
    p("Replace:   ", "foo".replace("o", "0", true, 1))
    p("Split:     ", "a-b-c-d-e".split("-"))
    p("ToLower:   ", "TEST".to_lower())
    p("ToUpper:   ", "test".to_upper())

This script demonstrates various string operations in GDScript. Here’s an explanation of the functions:

  1. GDScript doesn’t have a direct equivalent to Contains, but we can use find() which returns -1 if the substring is not found.
  2. count() returns the number of occurrences of a substring.
  3. begins_with() checks if a string starts with a given substring.
  4. ends_with() checks if a string ends with a given substring.
  5. find() returns the index of the first occurrence of a substring.
  6. join() is called on the separator string and takes an array of strings to join.
  7. repeat() creates a new string by repeating the original string.
  8. replace() replaces all occurrences of a substring with another string.
  9. replace() with additional parameters allows replacing only a specific number of occurrences.
  10. split() divides a string into an array of substrings.
  11. to_lower() converts a string to lowercase.
  12. to_upper() converts a string to uppercase.

To run this script, save it as a .gd file and attach it to a Node in your Godot project. The output will be printed to the Godot output panel when the scene is run.

Note that GDScript, being designed for game development, has a slightly different set of string functions compared to general-purpose languages. However, it provides similar functionality for most common string operations.