You are on page 1of 42

# Fundamentals of Programming: Built-in

functions
< A-level Computing | AQA | Paper 1 | Fundamentals of programming

## Exception handling Built-in functions

You need to be familiar with several programming routines that come built into most common
programming languages. These routines are very useful and should save you a lot of effort in writing
code to perform common tasks. You might be asked to use them in the exam so learn them!

Contents
[hide]

1Arithmetic functions

o 1.1Round

o 1.2Truncation

## 2String handling functions

o 2.1Length

o 2.2Position

o 2.3Substring

o 2.4Concatenation

## o 2.5String conversion functions

Arithmetic functions
You'll have to be familiar with several
Round
The round function is used to round numbers to a limited number of decimal places using
the Math.Round() function

## Math.Round(1.94, 1) 'Returns 1.9

Math.Round(1.95, 1) 'Returns 1.9 !0.5 rounds down!
Math.Round(1.96, 1) 'Returns 2.0
Math.Round(1.9445, 2) 'Returns 1.94
Math.Round(1.9545, 3) 'Returns 1.954
Math.Round(6.765, 2) 'Returns 6.76
Math.Round(1.9445) 'Returns 2 - the equivalent of saying round to 0 dp

Truncation
The truncate function returns the integer part of a number, regardless of the decimal places.

Math.Truncate(19.45) 'Returns 19
Math.Truncate(19.9999) 'Returns 19

This is particularly useful when you are trying to perform DIV in modular arithmetic.
Extension: Random numbers
An essential part of most games is the ability to use random numbers. These might be used to randomly place gold coins on a ma

## Dim rndGen As New Random()

Dim randomNumber As Integer
randomNumber = rndGen.Next()

The above code will give you a random number between 1 and 2,147,483,647. You might well require a number that is a little sm
and 10 you can use the following:

randomNumber = rndGen.Next(5,10)

So how exactly can we use this? Take a look at the following game:

## Dim rndGen As New Random()

Dim randomNumber As Integer
Dim guess as Integer
randomNumber = rndGen.Next(1,100)
console.writeline("Please guess the random number between 1 and 100")
Do
if guess > randomNumber
console.writeline("Too High")
end if
if guess < randomNumber
console.writeline("Too Low")
end if
Loop While guess <> randomNumber
console.writeline("Well done, you took x guesses to find it!")

Adjust the code above to tell the user how many guesses they took to find the random number. HINT: you'll need a variable
[Expand]
Exercise: Arithmetic function
What does the following code output:

## dim num1 as single = 12.75

dim num2 as single = 12.499
dim total as single

num2 = Math.Round(num2, 1)
num1 = Math.Truncate(num1)
total = num1 + num2
console.writeline(Math.Round(total))

[Expand]
Write some code to output the integer part of a number input by the user

[Expand]
Write code to output the integer and decimal parts of an input number:
Code Output

## Please insert a decimal number: 13.78

The whole number part of this number is: 13
The decimal part is: 0.78

[Expand]

## String handling functions

Very popular examination questions involve manipulating strings. These simple functions will help
Length
This function is used to find the length of any string you pass it, counting all the characters, including
the spaces. In visual basic to find the length of a string we use the Len("some string") function
that returns the integer length of the string that it has been passed:
someText = "Gary had a little lamb"
Console.writeline(Len(someText))

Code Output

22

Position
This function allows us to find the position of an item within a given string and returns the position's
location. In visual basic this is performed by the following command: InStr([string],
[item]) For example we might want to find the location of an end of a sentence by looking for a
fullstop:

someText = "Gary had a little lamb. His fleece was white as snow."
Console.writeline(InStr(someText,"."))

Code Output

23
We can also use this command to search for strings within strings. For example if we were to look for
to see if a sentence contained a certain name:

someText = "Gary had a little lamb. Dave's fleece was white as snow."
Console.writeline(InStr(someText,"Dave"))

Code Output

25
If the search item is not contained in the string then it will return 0

someText = "Gary had a little lamb. Dave's fleece was white as snow."
Console.writeline(InStr(someText,"Julie"))

Code Output

Substring
This function allows you to snip items out of a string and return a substring. Visual Basic uses the
following command: [string].Substring([startPosition],[lengthOfReturnString]) .
For example we might want to find the local number from a landline phone number we have been
given. We'll have to ignore the area code:

phone = "(01234)567890"
local = phone.Substring(7, 6)
console.writeline(local)

Code Output

567890

Concatenation
This function allows you to stick strings together (concatenate) so that you can start to build strings
using variables. Visual Basic uses the following command: [stringA & stringB] For example
we might have a users name stored in a variable dim name as string and a greeting that we
would like to give them:

name = "Charles"
console.writeline("Hello " & name & ". How are you today?")

Code Output

## String conversion functions

When you declare a variable you give it a datatype. This datatype restricts the values that you can
place into the variable. For example:
dim age as integer
would allow: age = 34
would NOT allow: age = "cabbages"
This seems to make sense, but what would happen when you try to place a real number
into a integer:

## dim age as integer

age = 34.3
console.writeline(age)

Code Output
34
This might seem OK, but in other lanuages we might run into trouble. To perform this we
would have to convert from one datatype to another:

## dim age as decimal

age = 34.3
console.writeline(age)
age = CInt(34.3) 'converts the decimal into an integer
console.writeline(age)

Code Output

34.3 34
Exercise: String functions
Write a short program to tell someone how many letters they have in their name (just in case they don't know!), for
Code Output

Input: Fremlin
Hello Fremlin, you have 7 letters in your name.

[Expand]
Some people have stupidly typed their firstname and their surname into a database, write some code to display the f

Code Output

## Input: Elizabeth Sheerin

Firstname: Elizabeth
Surname: Sheerin

[Expand]
A telephone number has been typed into a computer as a string: (01234)567890

## Write some code to output the number without brackets:

Code Output

Input: (01234)567890
Output: 01234567890

[Expand]
A similar question to the one above, telephone numbers are currently stored in a very unreadable format: 01234567
5 figures are the area code:

## This should then be output as:

Code Output

Input: 01234567890
Output: (01234)567890

[Expand]
Extension: REGEX
You will often want to check the format of a string being input and if it is incorrect you will want it to be submitted
meaning that they shouldn't be inputting any letters or spaces, and it should start with a capital letter:

Code Output

## Name of best friend: Beanie(CORRECT)

Name of best friend: jonny5(STOP THIS)
To do this we can match the input string against some rules, regular expressions or regex, in this case we only want
[A-Z][a-z]+

## [A-Z] - start exactly one instance of a capital letter

[a-z]+ - followed by as many lower case letters as you like (that's what the + means)

Another example might be checking for the correct spelling of a famous composer:

## "Handel", "Hndel", and "Haendel"

We can check this using the pattern H(|ae?)ndel . Let's take a look at what this means:

## (|ae?) - includes an or (the | symbol) an a followed by an optional e ( e? means the e is optiona

Most regular expression tools provide the following operations to construct expressions.
Boolean "or"
A vertical bar separates alternatives. For example, gray|grey can match "gray" or "grey".
Grouping
Parentheses are used to define the scope and precedence of the operators (among other uses). For example, gr
"gray" and "grey".
Quantification
A quantifier after a token (such as a character) or group specifies how often that preceding element is allowed t

? The question mark indicates there is zero or one of the preceding element. For example, colou?r matc

* The asterisk indicates there is zero or more of the preceding element. For example, ab*c matches "ac",

+ The plus sign indicates there is one or more of the preceding element. For example, ab+c matches "abc

Most programming languages have regular expression functions. In VB.NET we can use regular expressions b

## ' this code enforces the name rule from earlier

to/from integer, real, date/time.

## A-level Computing/AQA/Paper 1/Fundamentals

of programming/String-handling
< A-level Computing | AQA | Paper 1 | Fundamentals of programming

Contents
[hide]

## 1String handling functions

o 1.1Length

o 1.2Position

o 1.3Substring

o 1.4Concatenation

## o 1.5String conversion functions

String handling functions
Very popular examination questions involve manipulating strings. These simple functions will help
Length
This function is used to find the length of any string you pass it, counting all the characters, including
the spaces. In visual basic to find the length of a string we use the Len("some string") function
that returns the integer length of the string that it has been passed:

## someText = "Gary had a little lamb"

Console.writeline(Len(someText))

Code Output

22

Position
This function allows us to find the position of an item within a given string and returns the position's
location. In visual basic this is performed by the following command: InStr([string],
[item]) For example we might want to find the location of an end of a sentence by looking for a
fullstop:
someText = "Gary had a little lamb. His fleece was white as snow."
Console.writeline(InStr(someText,"."))

Code Output

23
We can also use this command to search for strings within strings. For example if we were to look for
to see if a sentence contained a certain name:

someText = "Gary had a little lamb. Dave's fleece was white as snow."
Console.writeline(InStr(someText,"Dave"))

Code Output

25
If the search item is not contained in the string then it will return 0

someText = "Gary had a little lamb. Dave's fleece was white as snow."
Console.writeline(InStr(someText,"Julie"))

Code Output

Substring
This function allows you to snip items out of a string and return a substring. Visual Basic uses the
following command: [string].Substring([startPosition],[lengthOfReturnString]) .
For example we might want to find the local number from a landline phone number we have been
given. We'll have to ignore the area code:

phone = "(01234)567890"
local = phone.Substring(7, 6)
console.writeline(local)

Code Output

567890

Concatenation
This function allows you to stick strings together (concatenate) so that you can start to build strings
using variables. Visual Basic uses the following command: [stringA & stringB] For example
we might have a users name stored in a variable dim name as string and a greeting that we
would like to give them:

name = "Charles"
console.writeline("Hello " & name & ". How are you today?")

Code Output

## String conversion functions

When you declare a variable you give it a datatype. This datatype restricts the values that you can
place into the variable. For example:
dim age as integer
would allow: age = 34
would NOT allow: age = "cabbages"
This seems to make sense, but what would happen when you try to place a real number
into a integer:

## dim age as integer

age = 34.3
console.writeline(age)

Code Output

34
This might seem OK, but in other lanuages we might run into trouble. To perform this we
would have to convert from one datatype to another:

## dim age as decimal

age = 34.3
console.writeline(age)
age = CInt(34.3) 'converts the decimal into an integer
console.writeline(age)

Code Output

34.3 34
Exercise: String functions
Write a short program to tell someone how many letters they have in their name (just in case they don't know!), for
Code Output

Input: Fremlin
Hello Fremlin, you have 7 letters in your name.

[Expand]
Some people have stupidly typed their firstname and their surname into a database, write some code to display the f

Code Output

## Input: Elizabeth Sheerin

Firstname: Elizabeth
Surname: Sheerin

[Expand]
A telephone number has been typed into a computer as a string: (01234)567890

## Write some code to output the number without brackets:

Code Output

Input: (01234)567890
Output: 01234567890

[Expand]
A similar question to the one above, telephone numbers are currently stored in a very unreadable format: 01234567
5 figures are the area code:

## This should then be output as:

Code Output

Input: 01234567890
Output: (01234)567890

[Expand]
Extension: REGEX
You will often want to check the format of a string being input and if it is incorrect you will want it to be submitted
meaning that they shouldn't be inputting any letters or spaces, and it should start with a capital letter:

Code Output

## Name of best friend: Beanie(CORRECT)

Name of best friend: jonny5(STOP THIS)
To do this we can match the input string against some rules, regular expressions or regex, in this case we only want
[A-Z][a-z]+

## [A-Z] - start exactly one instance of a capital letter

[a-z]+ - followed by as many lower case letters as you like (that's what the + means)

Another example might be checking for the correct spelling of a famous composer:

## "Handel", "Hndel", and "Haendel"

We can check this using the pattern H(|ae?)ndel . Let's take a look at what this means:

## (|ae?) - includes an or (the | symbol) an a followed by an optional e ( e? means the e is optiona

Most regular expression tools provide the following operations to construct expressions.
Boolean "or"
A vertical bar separates alternatives. For example, gray|grey can match "gray" or "grey".
Grouping
Parentheses are used to define the scope and precedence of the operators (among other uses). For example, gr
"gray" and "grey".
Quantification
A quantifier after a token (such as a character) or group specifies how often that preceding element is allowed t

? The question mark indicates there is zero or one of the preceding element. For example, colou?r matc

* The asterisk indicates there is zero or more of the preceding element. For example, ab*c matches "ac",

+ The plus sign indicates there is one or more of the preceding element. For example, ab+c matches "abc

Most programming languages have regular expression functions. In VB.NET we can use regular expressions b

## ' this code enforces the name rule from earlier

Notes
PAGES47

This preview shows pages 3245. Sign up to view the full content.

32

## view the full version.

View Full Document

Example
4StructureFullNa
meDimfirstNameAs
StringDimlastNam
eAs StringEnd
Structure33Structur
eStudentDimname
AsFullNameDimcre
dits()As IntegerEnd
StructurePrivate
SubbtnGet_Click(...
)HandlesbtnGet.Cli
ckDimnumYearsAs
IntegerDimpersonA
sStudentStructure
"FullName"contain
ed, or
nested,inside
Student
Example
4
continue
dtxtResult.Clear()
person.name.firstN
ame =
InputBox("First
Name:")person.na
me.lastName =
InputBox("Second
Name:")numYears
=CInt(InputBox("N
umber of years "&
_"completed:"))34R
eDimperson.credit
s(numYears -
1)ForiAs Integer=
0TonumYears -
1person.credits(i)=
CInt(InputBox("Cre
dits in year "_& i +
1))NextDetermineS
tatus(person)End
Sub
How to Easily Extract
From Any String Without
Using VBA InStr
AUGUST 18, 2015 BY PAUL KELLY 13 COMMENTS

The VBA InStr function is one of the most used functions in VBA. It is used to find a
string within a string and indeed it does a very fine job.

However, it is often used to help extract part of a string and for this task it performs

If you have found string extraction in VBA to be a painful process, then read on. This
post will show you a simpler and better way using three real world examples!
Contents [hide]
1 A Quick Guide to this Post
2 Quick Reference Notes
3 Introduction
4 When VBA InStr, Left, Right and Mid are useful
o 4.1 Using InStr to check if string contains text
o 4.2 Extracting with Left, Right and Mid
5 Dealing with Strings of Varying Lengths
o 5.1 Using the VBA InStr Function with Left
o 5.2 Using the VBA InStr Function with Right
o 5.3 Using the VBA InStr Function with Mid
6 The Split Function
7 Example 1: Getting part of a file name
8 Example 2: IP Address Range
9 Example 3: Check if a filename is valid
10 Conclusion
11 Whats Next?
12 Get the Free eBook

## A Quick Guide to this Post

The following table provides a quick reference guide to what is covered in this post.

## 1234ABC334 Fixed size get chars 5,6,7 Mid(s,5,3)

"John Henry Smith" Variable size get first name Split(s," ")(0)

"John Henry Smith" Variable size get second name Split(s," ")(1)

"John Henry Smith" Variable size get third name Split(s," ")(2)

"John Henry Smith" Variable size Get last name Dim v As Variant
v = Split(s, " ")
lastname= v(UBound(v))

## Quick Reference Notes

To find out more about the items referenced in the post check out the following links

If you would like to know more about the InStr or InStrRev functions then please

If you would like to know more about Mid, Left or Right functions then check
out Extracting Part of a String.

For more about the Split function check out String to Array using Split.

## The Like operator is covered in Pattern Matching

I use Debug.Print in my examples. It prints values to the Immediate Window which you
can view by pressing Ctrl and G (or select View->Immediate Window)

Introduction
In this post, Im going to show you a better way to extract values from a string than
using then VBA InStr function with Left, Right or Mid.

## Section 2: How to extract from variable sized strings.

Section 3: How to extract from variable sized string using the Split function.

## When VBA InStr, Left, Right and

Mid are useful
If you want to check if a string contains a value then InStr is fine for the job. If you want
to do a simple extraction then Left, Right and Mid also fine to use.

## Using InStr to check if string contains

text
In the following example, we check if the name contains Henry. If the return value of
InStr is greater than zero then the string contains the value we are checking for.

## If InStr("John Henry Smith", "Henry") > 0 Then

Debug.Print "Found"

End If

## Extracting with Left, Right and Mid

The Left function is used to get characters from the left of a string.
The Right function is used to get characters from the right of a string.
The Mid function is used for the middle of the string. It is the same as Left except that
you give it a starting position.
Sub ExtractString()

## Debug.Print Mid(s, 6, 4) ' Prints 7789

End Sub

These three functions work fine if the text you require is always the same size and in the
same place. For other scenarios, they require the use of InStr to find a particular
position in the string. This makes using them complicated.
Use Left, Right or Mid when the characters will always be in the same position.

## Dealing with Strings of Varying

Lengths
Many of the strings you will deal with will be of different lengths. A simple example is
when you are dealing with a list of names. The string length and part you require(e.g. the
first name) may be of different each time. For example

Brooke Hilt
Zack Kinzel
Eddy Wormley
Kaitlyn Rainer
Jacque Trickett
Kandra Stanbery
Margo Hoppes
Berenice Meier
Garrett Hyre

(If you need random list of test names then try this random name generator)

## Using the VBA InStr Function with Left

In the following example, we are going to get the first name from a string. In this string
the first name is the name before the first space.

We use the VBA InStr function to get the position of the first space. We want to get all
the characters before the space. We subtract one from the position as this gives us the
position of the last letter of the name.
Sub GetFirstname()

## Debug.Print Left(s, lPosition)

s = "Lorraine Huggard"

## Debug.Print Left(s, lPosition)

End Sub

Lets look at the first example in the above code. The first space is at position 5. We
substract 1 so which gives us position 4. This is the position of the last letter of John
i.e.n.
We then give 4 to the Left function and it returns the first four characters e.g. John

We can perform the same task in one line by passing the return value from InStr to the
Left function.

Dim s As String

## Using the VBA InStr Function with Right

In this example, we will get the last word in the string i.e. Smith. We can use
the InStrRev function to help us. This is the same as InStr except it searches from the
end of the string.

Its important to note that InStrRev gives us the position from the start of the string .
Therefore, we need to use it slightly differently than we used InStr and Left.
Sub GetLastName()

Length = Len(s)

End Sub

## 4. We give 5 to the Right function and get back Smith

Using the VBA InStr Function with Mid
In the next example, we will get Henry from the string. The word we are looking for is
between the first and second space.

## We will use the Mid function here.

Sub GetSecondName()

## secondChar = InStr(firstChar, s, " ")

' Get numbers of characters. Result is 5

## Debug.Print Mid(s, firstChar, count)

End Sub

You can see this is tricky to do and requires a bit of effort to figure out. We need to find
the first space. Then we need to find the second space. Then we have to substract one
from the other to give us the number of characters to take.

If have a string with a lot of words then this can get very tricky indeed. Luckily for us
there is a much easier was to extract characters from a string. Its called
the Split function.
The Split Function

We can use the Split function to perform the above examples. The Split function splits a
string into an array. Then we can easily access each individual item.

Lets try the same three examples again and this time we will use Split.

## Debug.Print Split(s, " ")(2) ' Smith

Boom! What a difference using Split makes. The way it works is as follows

## 1. The Split function splits the string wherever there is a space.

2. Each item goes into an array location starting at location zero.

## 3. Using the number of a location we can access an array item.

The following table shows what the array might look like after Split has been used.

Note: the first position in the array is zero. Having zero based arrays is standard in
programming languages.

0 1 2

## John Henry Smith

In the above code we split the string each time we used it. We could also split the string
once and store it in an array variable. Then we can access it when we want.

Sub SplitName()

## Debug.Print arr(2) ' Smith

End Sub

If you would like to know more about arrays then I wrote an entire post about them
called The Complete Guide to Using Arrays in Excel VBA.
In the next sections, we will look at some real world examples. You will see the benefit
of using Split instead of the InStr function.

Please feel free to try these yourself first. It is a great way to learn and you may have fun
trying to figure them out(or maybe thats just me!)

## Example 1: Getting part of a file

name
Imagine we want to extract the numbers from the following filenames

VB_23476_Val.xls
VV_987_Val.txt
VZZA_12223_Val.doc

This is similar to the example about where we get the second item. To get the values
here we use the underscore(i.e. _) to split the string. See the code example below

Sub GetNumber()

## Debug.Print Split("ABBZA_12223_Val.doc", "_")(1)

End Sub

In the real world you would normally read strings like these from a range of cells. So lets
say these filenames are stored in cells A1 to A3. We will adjust the code above slightly
to give us:

Dim c As Range

Next c

End Sub

## Example 2: IP Address Range

The example here is taken from a question on the StackOverflow website.

The user has a string with an IP address in the format BE-ABCDDD-DDS 172.16.23.3.

## BE-ABCDDD-DDS 172.16.23.3 is valid

BE-ABCDDD-DDS 172.25.23.3 is valid

## BE-ABCDDED-DDS 172.14.23.3 is not valid

BE-ABCDDDZZ-DDS 172.32.23.3 is not valid

This is how I would do this. First I split the string by the periods. The number we are
looking for is between the first and second period. Therefore, it is the second item.
When we split the string it is placed at position one in the array (remember that the array
starts at position zero).

## The resulting array will look like this

0 1 2 3

BE-ABCDDD-DDS 172 31 23 3

End Sub

## Example 3: Check if a filename is

valid
In this final example, we want to check that a file name is valid. There are three rules
1. It must end with .pdf

2. It must contain AA

## The following tables shows some valid and invalid items

Filename Status

AA1234.pdf valid

AA_ljgslf_1234.pdf valid

## 1234 AA.pdf Not valid - AA does not come before 1234

12_AA_1234_NM.pdf Valid

Sub UseInstr()

## Dim lPos As Long: lPos = InStr(f, "AA")

' Search for 1234 and ensure last four chars are .pdf

## Debug.Print InStr(lPos, f, "1234") > 0 And Right(f, 4) = ".pdf"

End Sub

This code is very messy. Luckily for us, VBA has Pattern Matching. We can check the
pattern of a string without having to search for items and positions etc. We use
the Like operator in VBA for pattern matching. The example below shows how to do it.

Sub UsePattern()

## Debug.Print f Like pattern ' True

End Sub

In the above example, the asterisk in the pattern refers to any number of characters.

## * any group of characters

AA the exact characters AA
* any group of characters
1234 the exact characters 1234
* any group of characters
.pdf the exact characters .pdf

To show this works correctly, lets try it on all the example names in the table
Sub UsePatternTest()

Dim f As Variant

## Debug.Print f Like pattern

Next f

End Sub

The output is
True
True
False
False
True
To find out more about Pattern Matching and the Like keyword please check out this
post.

Conclusion
InStr and InStrRev are really only useful for simple tasks like checking if text exists in a
string.

Left, Right and Mid are useful when the position of the text is always the same.

The Split function is the best way to extract from a variable string.

When trying to check the format of a string that is not fixed in size,
the Like keyword(i.e. Pattern Matching) will generally provide an easier solution.