Module 9: String Operations
Manipulating Text
Strings are just sequences of characters. OCR ERL gives you tools to measure, slice, and modify strings.
Length
The .length property returns how many characters are in a string.
word = "Computer"
print(word.length) // Outputs 8
Exercise: Length
Ask the user for their password. If its `.length` is less than 8, print "Too short!".
Case Conversion
Use .upper and .lower to convert the case of a string. This is useful for checking user input regardless of how they type it.
ans = input("Yes or No?")
if ans.upper == "YES" then
print("Confirmed")
endif
Exercise: Shout out
Ask the user for a word. Print out the same word completely in uppercase, and then completely in lowercase.
Substrings
The syntax is stringname.substring(startingPosition, length). Like arrays, strings are 0-indexed.
word = "Computer"
// Start at index 0 (C), grab 4 characters
print(word.substring(0, 4)) // Outputs "Comp"
// Start at index 4 (u), grab 2 characters
print(word.substring(4, 2)) // Outputs "ut"
Exercise: Initial Extractor
Write an algorithm that asks the user for their first name, and then their surname. Create a new variable called initials that contains the very first letter of their first name, and the first letter of their surname, converted to uppercase. Print the result.