Try This: Access Substrings
In the previous activity, a single character was accessed using an index, like set c to (char in (s) at (3)). Your projects can also view segments of strings by using a range instead of a single index number in the square brackets.
Let’s say you have a string named s:
- char in (s) at (5) — fifth character in a string
- substring of (s) from (3) of length (4) — third through sixth characters in a string
- substring of (s) from (0) of length (5) — beginning through the fifth character
- substring of (s) from (11) of length (length of (s)) — eleventh character through the end of the string.
In Makecode-speak, strings are considered immutable. Being immutable means that once created, a string cannot be changed. That doesn’t mean that s = “Have a nice day.” cannot be changed to s = “Have a GREAT day!” It just means that the original “Have a nice day.” string cannot be changed. A block can still grab parts of “Have a nice day.” and use them to create a new string that reads “Have a GREAT day!” The resulting string can even be assigned back to s.
The s variable starts as this string: “Have a nice day.” The second block adds “Have a ” + “GREAT” + ” day” + “!”. See how “Have a “ is s[:7] from the original string? Add the string “GREAT” to that, and then ” day” with a leading space, which is s[11:End], and lastly add “!”, and the string surgery is complete!
Example project: string_surgery_try_this
This project starts with “Have a nice day.” and then creates a new string sn with the “nice” portion of the original. After that, it demonstrates some more ways to access segments of an original string that were introduced above.
- Enter and name string_surgery_try_this.
- Click the Download button.
- Check the results in the serial terminal.
- Verify that it displays: