String Manipulation

typewriter

Learning Objectives


In this post we will focus on string manipulation techniques using five common techniques used in most procedural programming languages:

  • LEFT: to extract characters at the beginning of a string,

  • RIGHT: to extract characters at the end of a string,

  • LENGTH: to find out the number of characters in a string,

  • MID: to extract a set number of characters at a given position in a string,

  • LOCATE: to find if a substring is included in another string and if so return the position of this substring in the string.

LEFTRIGHTLENGTHMIDLOCATE
e.g. LEFT(myString, 5)

>>> to extract the first 5 characters of a string.

e.g. RIGHT(myString, 5)

>>> to extract the last 5 characters of a string.

e.g. LENGTH(myString)

>>> to retrieve the number of characters in a string.

e.g. MID(myString, 3, 5)

>>> to extract a set number of characters at a given position in a string.

e.g. LOCATE(“World”, “Hello World”)

>>> to find if a substring is included in another string and if so return the position of this substring in the string.
If the substring is not part of the string, the value -1 is returned.

Your Challenge


Check the code below which is based on the 5 string manipulation functions we mentioned above: Left, Right, Length, Mid, and Locate.

Your challenge is to tweak this code to ask the user to enter their school username in the following format:

  • Year Group Using two digits (e.g. “07” for year 7, “11” for year 11, “00” for staff members)
  • 1 character for their initial (first letter of their firstname)
  • The user’s lastname
  • A 2-digit code: “_S” for students, “_T” for teachers, “_A” for admin staff.

For instance the following usernames are valid usernames:


07jFox_S
09kJohnson_S
11rTaylor_S
00pJones_T
00jOliver_A

Your program should read the username and decide:

  • If the username is less than 6 characters long the program should ask the user to enter a valid username.
  • If the username does not contain the character “_” it should also ask the user to enter a valid username.
  • If the username is valid, the program should decide if the user is a member of staff or a student.
  • If they are a student the programme should find out their year group.
  • The program should also display the initial of the student as well as their lastame.
  • Finally the program should display whether the user is a Student, a Teacher or an Admin member of staff.

Did you like this challenge?

Click on a star to rate it!

Average rating 4.7 / 5. Vote count: 3

No votes so far! Be the first to rate this post.

As you found this challenge interesting...

Follow us on social media!