Example 75: Extract a Substring

Learn how to extract a substring from a string.


Write a program that extracts a substring from the left, right, or middle of a string.


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:

  1. Invalid length
  2. Starting index out of range
  3. Invalid substring length
  4. Length out of range

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.