String Handling Operations In Programming

One of the most common operations in programming is to manipulate string inputs. This is known as String Handling as we are using our programs to analyse and adjust data.

There are a number of diffent ways that we can analyse a string including:

Its length

The position of a character

Extracting a substring

After analysing a string for what it already contains, there are also ways to adjust and adapt a string for the needs of the program.

Casting

The act of casting is to transform one data type into another. If you are taking user input into your program, you will likely find that the program assumes that it is a string. If you actually wanted them to input a number, you can do one of two things. In python these would look like:

myNum = int(input("Enter a number"))

or

myNum = input("Enter a number")

if myNum.isnumeric() ==True:
   myNum = int(myNum)

This second version will check to see if the casting is possible, preventing errors if the data entered is not a number.

Concatenation

The term concatenation refers to creating a string by joining two or more strings together. In the pseudocode below, the string is joined to a string variable to create a single string.

name <– INPUT

greeting <– “Hello ” + name

OUTPUT greeting

Concatenation is particularly useful when outputing messages to the user with calculated values.

 

Ord & Chr

Another way of handling strings in programming is to convert alphanumeric data into its numerical format in a character set. The Ord and Chr operators allow characters to be swapped between their text and number formats using the ASCII character set.

These two operators allow for more efficient validation of strings an creation of random letters. In the python code below, a word game uses Chr to pay against the user.

found = False

guessed = []

while found == False:

    guess = random.randint(97,122)

    while guess in guessed:

        guess = random.randint(97,122)

    print("Is " + Chr(guess) + " your letter?)

 

Ord is just as powerful, and in the code below, it is used to create a range check for a letter instead of checking through the alphabet.

 

password = input("please enter your password: ")

if  (ord(password[0]) >=97) and (ord(password[0]) >=122):

    print("password starts with a lower case letter")

else:

    print("password invalid")

 

 

More For Members

Lesson Plan

Coming Soon!

Presentation

Coming Soon!

Homework

Coming Soon!

Not a member yet? Sign Up Here