Substring (Substr)
What is it?
The Substr function extracts a string from within another string, such as “corn” from “unicorn”, “monk” from “monkey” or “not” from “knotted”. The string you extract is known as a Substring.
What is the Syntax?
The Substr function’s syntax is as follows:
Substr( String, StartIndex, Length );
The String argument is the initial string you want to extract a substring from.
The StartIndex is the index number of the first character you want to extract. The first character in any string has the index 0, and you can work out the index of any other character by counting upwards from 0 for each character from left to right:
Character | E | L | E | P | H | A | N | T |
Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
As shown above, if your string is “ELEPHANT” and you want to extract the last three letters starting with “A”, you would use 5 as your startIndex value.
The Length argument is the number of characters you want your substring to contain. If you enter a length that exceeds the total number of characters between your index number and the end of the original string, the substring will contain all characters between the startIndex you specify and the end of the word.
For example, if you start a substring at the letter “I” in “QUESTION”, setting the substring length to 3 will result in the same result as a length of 4, 5 or any other number higher than 3. Because there are only three characters from the letter “I” to the end of the original string, even if you ask for a substring of length 50, you will only get “ION” as your substring.
Why might I want to use this?
When we discussed the Strlen function in the previous section, we discussed password validation for users setting up a new e-mail account. We can now use the Substr function to create a default ID for the user based on a supplied forename and surname. The format we use will be the first two letters of their forename, followed by the entirety of their surname.
To find the first two letter of their forename, we would use the Substr function as follows:
Substr( ForeName, 0, 2 );
Again, we use 0 for the index because 0 is always the index of a string’s first character. If the user’s forename was “John”, the above expression would evaluate to “Jo”. Next, we use the concatenation operator to join the substring “Jo” to the user’s surname, which in this example is “Smith”.
UserID := Substr( Forename, 0, 2 ) & Surname;
Using this expression, the default user ID for John Smith will be “JoSmith”.
<< Previous: String Length (Strlen) | Next: Character (Chr) >>