Example 75: Extract a Substring
Learn how to extract a substring from a string.
We'll cover the following
Problem
Write a program that extracts a substring from the left, right, or middle of a string.
Example
The following string has been used for the examples given in the table.
String: Four hundred and thirty two
Input | Output |
---|---|
getsub (str, 5, 7) | hundred |
leftsub (str, 4) | Four |
rightsub (str, 3) | two |
Try it yourself - getsub
Try to extract the substring on your own in the code widget below. If you get stuck, you can always refer to the solution provided.
❗Note: In the valid case, print the substring. In the invalid case, print the reason:
- Invalid length
- Starting index out of range
- Invalid substring length
- Length out of range
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.