String Operations
Lesson 19 of 48 in Coddy's GDScript for C++ Developers course.
std::string is a mutable value type: copying it makes an independent value, while references can alias the same string. GDScript String has value semantics and replacement methods return a new value. C++ mutation methods and GDScript returned-value methods therefore need different call patterns. Preserve an original C++ string by copying it first. Define trimming and replacement order explicitly because normalization can change accepted tokens. This example replaces an ASCII delimiter in a copy, leaving the task prefix-removal sequence unspecified.
Complete C++ comparison. Save the listed files together and compile the .cpp files with C++20; main is the entry point.
C++ file main.cpp:
#include <iostream>
#include <string>
#include <algorithm>
int main() { std::string s="a-b-a",t=s; std::replace(t.begin(),t.end(),'-','/'); std::cout << s << " " << t << '\n'; }
C++ output:
a-b-a a/b/aGDScript example file main.gd:
extends Node
func _ready() -> void:
var s: String = "a-b-a"
var t: String = s.replace("-","/")
print(s," ",t)GDScript output:
a-b-a a/b/aChallenge
EasyInputs text and prefix. Strip surrounding whitespace from text, then remove one matching prefix. Preserve interior spaces.
Input is one JSON array on stdin. The locked main parses it, calls the public APIs and prints result= followed by the returned text and a newline. No helper should print. Independent fixed probes verify required API behavior before the input case; they do not enforce implementation style.
Your code goes in exercise.gd. main.gd holds the supplied input/output code and cannot be edited. Keep each class_name type in its named file.
Try it yourself
extends Node
func contract_ok(data: Array) -> bool:
return true
func _ready() -> void:
var data: Array = JSON.parse_string(OS.read_string_from_stdin())
if not contract_ok(data):
print("API_CONTRACT_FAILED")
return
print("result=" + Exercise.solve(data))
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in GDScript for C++ Developers
1Scripts and Scalar Values
Run Script FilesText and CommentsBindings and TypesInteger ArithmeticBoolean ResultsRecap: Stock Label2Flow and Functions
Branches and ValuesPattern MatchingLoops and RangesTyped FunctionsDefault ArgumentsRecap: Command CountPractice on your own: Online GDScript compiler