Example 75: Extract a Substring

Learn how to extract a substring from a string.

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:

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

Get hands-on with 1400+ tech skills courses.