Small Steps I — Creating with Text and Numbers
Taking part of a string
Take Sm, the first two characters of Small.
What you will learn
A substring is a consecutive part of a string. Pass substring a starting position and the length to take.
Try it
Example · example.cpp
void small_main()
{
String word = "Small";
print(word.substring(1, 3));
}
Position 1 is m. Taking three characters from there gives mal. Omitting the length, as in substring(1), takes everything from position 1 to the end.
In a string of length 5, character positions are 0–4. Stay within those bounds when reading a character with brackets.
Expected output:
mal
Exercise
Take Sm, the first two characters of Small.
Exercise starter · exercise_starter.cpp
void small_main()
{
String word = "Small";
print(word.substring(1, 3));
}
Hint
Change the parts of the example that you need.
show solution
void small_main()
{
String word = "Small";
print(word.substring(0, 2));
}