Advertise here.
Showing posts with label VB. Show all posts
Showing posts with label VB. Show all posts

Tuesday, 28 August 2012

VB.NET Programming lesson #4 - String Handling


String handling is the use of various methods to manipulate a string into a form that a program needs it in. You will already know from a previous lesson that a string is a variable that stores text. All programs use text in some way since text is used to show messages to the user and for getting input from the user which makes string handling an important part of programming.

String concatenation

String concatenation means joining 2 strings together. To join 2 strings together you can use either an ampersand (&) or a plus (+). Here is an example that uses the ampersand to join 2 strings together with a space between them.

Imports Microsoft.VisualBasic
Imports System

Class StringHandling
   Shared Sub Main()
      Dim string1 As String = "Part one"
      Dim string2 As String = "Part two"
      Dim string3 As String = string1 & " " & string2
      Console.WriteLine(string3)
   End Sub
End Class

You can also use a plus instead of an ampersand.

Dim string3 As String = string1 + " " + string2

String handling commands

Visual Basic.NET has various useful commands for manipulating strings. The following are some of the commands you will use most often.

Upper and lower case

To change all the letters in a string to uppercase letters you can use the ToUpper command. You can use theToLower command to change them all to lowercase letters. Both of these commands and a lot of the others are called on the declared string object which means you use them by putting a dot after the name of the string followed by the command. Here is an example that demonstrates both of the commands.

Imports Microsoft.VisualBasic
Imports System

Class StringHandling
   Shared Sub Main()
      Dim MyString As String = "Some Text"
      Dim lower As String = MyString.ToLower()
      Dim upper As String = MyString.ToUpper()
      Console.WriteLine(lower)
      Console.WriteLine(upper)
   End Sub
End Class


Getting part of a string

You can use the Left command to get a certain number of characters from the left of a string and there is also a Right command that does the same from the right side of a string. Both commands take 2 paramaters. The first parameter is the string to work with and the second parameter is the number of characters to get from the string. Here is an example that takes 4 characters from the left of a string and also 4 characters from the right.

Imports Microsoft.VisualBasic
Imports System

Class StringHandling
   Shared Sub Main()
      Dim MyString As String = "Some Text"
      Dim LeftPart As String = Left(MyString, 4)
      Dim RightPart As String = Right(MyString, 4)
      Console.WriteLine(LeftPart)
      Console.WriteLine(RightPart)
   End Sub
End Class

You can use the Substring command to get part of a string from anywhere in a string. The Substringcommand has 2 parameters which are the position to start copying characters from and then the number of characters to copy. The start position parameter is a bit confusing because the numbering of the positions of a string start at 0 instead of one so you will have to substract 1 from the actual position in a string. So if you want to start from the 5th character in a string you must actually use 4 as the start position. The number of characters parameter does not start at 0 but rather from 1 because it is counting the number of characters to copy. The 2nd parameter is optional and if left out it will just keep going until the end of the string. Here is an example that uses Substring to extract the middle word in a string.

Imports Microsoft.VisualBasic
Imports System

Class StringHandling
   Shared Sub Main()
      Dim Fullname As String = "John Paul Smith"
      Dim MiddleName As String = Fullname.Substring(5, 4)
      Console.WriteLine(MiddleName)
   End Sub
End Class


Length of a string

You can get the number of characters in a string using the Length property of a string. The Length property is not a command but a property so you must not use brackets with it. Here is an example that prints out the length of a string.

Imports Microsoft.VisualBasic
Imports System

Class StringHandling
   Shared Sub Main()
      Dim MyString As String = "Some Text"
      Console.WriteLine(MyString.Length)
   End Sub
End Class


Searching a string

You can use the IndexOf command to find out if a string contains another string and at what position the string was found. The IndexOf command acts on a string and takes one parameter which is the string to find. It returns a number which is the position in the string that the string to find was found. The position numbering starts from 0 and not 1 so you need to be careful with it. If the string was not found then -1 is returned. Here is an example that shows how to find a string in another string using the IndexOf command.

Imports Microsoft.VisualBasic
Imports System

Class StringHandling
   Shared Sub Main()
      Dim MyString As String = "A needle in a haystack"
      Dim FoundPosition As Integer = MyString.IndexOf("needle")
      Console.WriteLine(FoundPosition)
   End Sub
End Class


Replacing parts of a string

You can use the Replace command to replace parts of a string. The command takes 2 parameters. The first parameter is the string to find in the string and the second parameter is the string to replace it with. Here is an example that replaces the word "dogs" with the word "cats".

Imports Microsoft.VisualBasic
Imports System

Class StringHandling
   Shared Sub Main()
      Dim MyString As String = "I like dogs"
      Dim NewString As String = MyString.Replace("dogs", "cats")
      Console.WriteLine(NewString)
   End Sub
End Class


Trimming

You can remove any spaces from both the beginning and the end of a string by using the Trim command. This is useful for when you ask a user to enter something because they sometimes add spaces by mistake. Here is an example of how to use it.

Imports Microsoft.VisualBasic
Imports System

Class StringHandling
   Shared Sub Main()
      Dim MyString As String = " Some Text "
      Dim NewString As String = MyString.Trim()
      Console.WriteLine(NewString)
   End Sub
End Class


String data type conversions

You often need to convert other data types such as integers to strings before you can output them to the user. For example, if you want to display a message to the user with a number that was calculated in the program then you will have to convert that number to a string and then concatenate it with the message text. TheConvert.ToString command will convert things to a string most of the time. All objects also have a ToStringcommand on them which produces a string representation of the object but this method is not as reliable asConvert.ToString because it sometimes produces unexpected results.

You can convert a string to a lot of other types using the various Convert methods such as Convert.ToInt32 to convert a string to an integer. This kind of thing is useful for when a user enters some text that needs to be converted to an integer before calculations can be done on it.

Here is an example that converts both from a string and to a string. It gets the user to enter 2 numbers and then adds them together and then outputs the result along with a nice message.

Imports Microsoft.VisualBasic
Imports System

Class StringHandling
   Shared Sub Main()
      Console.WriteLine("Please enter first number:")
      Dim Num1 As String = Console.ReadLine()
      Console.WriteLine("Please enter second number:")
      Dim Num2 As String = Console.ReadLine()
      Dim int1 As Integer = Convert.ToInt32(Num1)
      Dim int2 As Integer = Convert.ToInt32(Num2)
      Dim result As Integer = int1 + int2
      Dim message As String = "The result is " & Convert.ToString(result)
      Console.WriteLine(message)
   End Sub
End Class


Characters and strings

Strings are actually just sequences of characters. If you want to get an individual character within a string all you need to do is put brackets behind the name of the string with the number of the position of the character you want. This position is an index which means it starts at 0 and not at 1. Here is an example that gets the 3rd character (index 2) from a string.

Imports Microsoft.VisualBasic
Imports System

Class StringHandling
   Shared Sub Main()
      Dim MyString As String = "Something"
      Dim MyChar As Char = MyString(2)
      Console.WriteLine(MyChar)
   End Sub
End Class


Escaping characters

Visual Basic.NET uses double quotes around the contents of a string as you already know very well by now. The problem with this is that when you want to put actual double quotes in a string then it thinks that you are closing the string. To get around this problem you need to escape the double quotes by using 2 of them instead of 1. The 2 double quotes will show up as 1 double quote in the program.

Imports Microsoft.VisualBasic
Imports System

Class StringHandling
   Shared Sub Main()
      Dim MyString As String = "Putting ""quotes"" in a string"
      Console.WriteLine(MyString)
   End Sub
End Class


Other string handling commands

There are many more string handling commands that you can use but we have covered the most useful ones. If you are interested in more of them then have a look at Microsoft's String class members reference.


Practice

Write a program that asks the user for their full name. Extract the first name and the last name from the full name entered by the user by using the commands you have learnt in this lesson. Finding the position of the space between the two names will help you solve this problem.

VB.NET Programming lesson #3 - Variables


A variable is something that is used in a program to store data in memory. Variables are used for storing the data that a program is busy working with. Variables can store all sorts of different types of data including things like numbers and text. Variables are important because it is almost impossible to write a useful program that doesn't use them.

Declaring a variable

Here is an example of how to declare a variable followed by an explanation.

Imports Microsoft.VisualBasic
Imports System

Class Variables

   Shared Sub Main()
      Dim MyInt As Integer
   End Sub

End Class

The variable is declared using the Dim keyword followed by the name of the variable which in this case isMyInt. After that is the As keyword followed by the data type of the variable which is an Integer in this example. An Integer is a variable that stores numbers. There are different types of variables for storing different types of data which you will learn about later.

Setting the value of a variable

You set the value of a variable using an equals sign (=). Here is an example of how to set the value of a variable.

Imports Microsoft.VisualBasic
Imports System

Class Variables

   Shared Sub Main()
      Dim MyInt As Integer
      MyInt = 5
   End Sub

End Class

In the above example the variable called MyInt has been set to the value of 5.

The Console.WriteLine command can be used to display the value of a variable. You must not use double quotes with Console.WriteLine when using a variable like you had to when printing words on the screen because then the compiler thinks you want to print the name of the variable instead of the value it holds. Here is how you print the value of a variable.

Imports Microsoft.VisualBasic
Imports System

Class Variables

   Shared Sub Main()
      Dim MyInt As Integer
      MyInt = 5
      Console.WriteLine(MyInt)
   End Sub

End Class

You can set the value of a variable at the same time as you declare it which is called initializing a variable. Here is an example of how to initialize a variable.

Imports Microsoft.VisualBasic
Imports System

Class Variables

   Shared Sub Main()
      Dim MyInt As Integer = 7
   End Sub

End Class

You can declare more than one variable by adding another variable name to the same declaration in which case you must separate the variable names using a comma. Another way of doing it is to just declare another variable on a new line which a lot of programmers prefer doing because then the variables can be initialized easily.

Imports Microsoft.VisualBasic
Imports System

Class Variables

   Shared Sub Main()
      Dim MyInt1, MyInt2 As Integer
      Dim MyInt3 As Integer

   End Sub

End Class

Calculations using variables

You can perform calculations on variables using one of the 4 basic operations which are addition, subtraction, multiplication and division. The result of an operation must be stored in a variable otherwise it is lost. Here is an example in which the numbers 2 and 3 are added together and the result is stored in a variable calledMyInt which is printed on the screen.

Imports Microsoft.VisualBasic
Imports System

Class Variables

   Shared Sub Main()
      Dim MyInt As Integer
      MyInt = 2 + 3
      Console.WriteLine(MyInt)
   End Sub

End Class

You can see from the example above that the plus sign (+) is used for adding numbers. Here are the signs for the 4 operations.

+Add
-Subtract
*Multiply
/Divide

You can use variables in calculations just like you can use numbers. Here is an example in which 2 variables are declared and given values and then one is subtracted from the other and the result is stored in a third variable.

Imports Microsoft.VisualBasic
Imports System

Class Variables

   Shared Sub Main()
      Dim MyInt1 As Integer = 10
      Dim MyInt2 As Integer = 8
      Dim Result As Integer
      Result = MyInt1 - MyInt2
      Console.WriteLine(Result)
   End Sub

End Class

Data types

So far we have only been using the Integer data type which can store only numbers. If you want to store other types of data then you need to use a different data type.

The String data type is used for storing text. When you set the value of a string to some text you must surround it with double quotes because this tells the compiler that the text between the quotes is some text and not part of the code that the program must run. Here is an example of how to declare a string called MyString and set its value.

Imports Microsoft.VisualBasic
Imports System

Class Variables

   Shared Sub Main()
      Dim MyString As String
      MyString = "Some text"
      Console.WriteLine(MyString)
   End Sub

End Class

The Char data type is similar to a String except that you can only store 1 character in it. Most of the time you will use Strings instead of Chars but it is still important to understand how Chars work. Here is an example of how to declare a Char variable called MyChar and set its value to the letter V.

Imports Microsoft.VisualBasic
Imports System

Class Variables

   Shared Sub Main()
      Dim MyChar As Char
      MyChar = "V"
      Console.WriteLine(MyChar)
   End Sub

End Class

Integers can only store whole numbers and can't store numbers with a decimal point. To be able to work with numbers with a decimal point you must use the Decimal data type. Here is an example in which the number 10 is divided by 4 which gives a result that has a decimal point and therefore needs to be stored in the Decimal data type.

Imports Microsoft.VisualBasic
Imports System

Class Variables

   Shared Sub Main()
      Dim MyDec As Decimal
      MyDec = 10 / 4
      Console.WriteLine(MyDec)
   End Sub

End Class

The Boolean data type is used for storing either the value True or the value False and nothing else. It doesn't seem very useful but you will find later that it actually is. Understanding how Booleans work is very important for helping you understand how certain other things in programming work which you will come across later. Here is an example of how to declare a Boolean variable called MyBool and set its value to True and to False.

Imports Microsoft.VisualBasic
Imports System

Class Variables

   Shared Sub Main()
      Dim MyBool As Boolean
      MyBool = True
      Console.WriteLine(MyBool)
      MyBool = False
      Console.WriteLine(MyBool)
   End Sub

End Class

There are many more data types but the ones you have learnt so far cover the most common things you will come across in VB.NET programming. Your knowledge of the data types you have learnt will be enough to help you figure out how to use any of the other data types.

Storing user input

If you want to get the user to type something in and use it in your program then you can do that by using theConsole.ReadLine command which waits for the user to type some text and press Enter. When the user has pressed Enter the text the user entered is returned by Console.ReadLine so you have to store the value returned by the command in a variable. Here is an example in which the user is asked to type in some text and then the text the user entered is printed out again.

Imports Microsoft.VisualBasic
Imports System

Class Variables

   Shared Sub Main()
      Console.WriteLine("Please enter something:")
      Dim EnteredText As String
      EnteredText = Console.ReadLine()
      Console.WriteLine("You entered:")
      Console.WriteLine(EnteredText)
   End Sub

End Class

Type conversions

You will often have the need to convert variables to other data types. For example the Console.ReadLinecommand only reads in Strings so if you want the user to enter a number you have to convert the String that was read in to an Integer. There are quite a few different ways of converting between data types but you will only learn a few of them right now.

The first way of converting between data types is using a group of commands that start with the letter C. There is a command called CInt for example which is used to convert other data types such as Strings to Integers. Here is an example of how to use it in which the user is asked to enter a value which is stored in a String and then converted to an Integer using CInt and then shown again to the user.

Imports Microsoft.VisualBasic
Imports System

Class Variables

   Shared Sub Main()
      Console.WriteLine("Please enter a number:")
      Dim EnteredText As String
      EnteredText = Console.ReadLine()
      Dim MyInt As Integer
      MyInt = CInt(EnteredText)
      Console.WriteLine("The converted value is:")
      Console.WriteLine(MyInt)
   End Sub

End Class

Here are the most useful C conversion commands:
CInt (Convert to Integer)
CStr (Convert to String)
CChar (Convert to Char)
CDec (Convert to Decimal)
CBool (Convert to Boolean)

Another way to convert between types is to use the commands that begin with Convert.To . The .To is followed by the data type such as Convert.ToString. The command for converting to an Integer in this way isConvert.ToInt32. The advantage of the Convert commands over the C commands is that they are also used in programming languages such as C# which you might want to use one day. Here is an example that is the same as the previous one but using Convert.ToInt32 instead of CInt.

Imports Microsoft.VisualBasic
Imports System

Class Variables

   Shared Sub Main()
      Console.WriteLine("Please enter a number:")
      Dim EnteredText As String
      EnteredText = Console.ReadLine()
      Dim MyInt As Integer
      MyInt = Convert.ToInt32(EnteredText)
      Console.WriteLine("The converted value is:")
      Console.WriteLine(MyInt)
   End Sub

End Class

Here are the most useful Convert commands:
Convert.ToInt32 (Convert to Integer)
Convert.ToString (Convert to String)
Convert.ToChar (Convert to Char)
Convert.ToDecimal (Convert to Decimal)
Convert.ToBoolean (Convert to Boolean)

The CType command can be used for when the data type you want to convert to doesn't have either one of the above conversion methods because it can convert to any type. CType takes 2 parameters which are the value to be converted and then the name of the data type to convert to. Here is the same example from above again but this time it uses CType.

Imports Microsoft.VisualBasic
Imports System

Class Variables

   Shared Sub Main()
      Console.WriteLine("Please enter a number:")
      Dim EnteredText As String
      EnteredText = Console.ReadLine()
      Dim MyInt As Integer
      MyInt = CType(EnteredText, Integer)
      Console.WriteLine("The converted value is:")
      Console.WriteLine(MyInt)
   End Sub

End Class

Constants

A constant is a variable whose value can't be changed. You use a constant when you specifically don't want the value of a variable to change during the execution of your program. Constants can be used for things like the company name of the company which wrote the program because the company name must not change anywhere. All you have to do to declare a constant is change the Dim keyword in the normal variable declaration to Const. The value of the constant must be initialized on the same line as it is declared otherwise you will get a compiler error. Here is an example of how to declare a constant for a company name.

Imports Microsoft.VisualBasic
Imports System

Class Variables

   Shared Sub Main()
      Const CompanyName As String = "ABC Company"
      Console.WriteLine(CompanyName)
   End Sub

End Class

Practice

Write a program that asks the user to enter 2 numbers. The program must then add the 2 numbers together and print out the result. Change the program to work with subtraction, multiplication and division and test them all out. Remember that you will have to convert the user's input to an Integer before it can be used in a calculation.

VB.NET Programming lesson #2 - Your First Program


The first thing you need to do is create a source file. A source file is a text file that contains the source code or in other words the commands that the program must run. VB.NET source files usually have the file extension .vb. We are going to be using Notepad to write our VB.NET code.

Create a text file called hello.vb somewhere where you can easily find it. I am going to create a folder calledvbnet in the root of my C drive and then create the source file in there which might be a good idea for you too. Make sure you have the file open in Notepad and then add the lines of code that follow to your source file. Each line of code is explained as I go along.

Imports Microsoft.VisualBasic
Imports System

The Imports keyword is used to import namespaces. This means that you can use the commands in that namespace. The Microsoft.VisualBasic namespace contains commands that you will be using very often that are specific to Visual Basic.NET. The System namespace contains a lot of useful commands and classes, one of which is the command to write things on the screen which you will see later. There are lots of other namespaces to import but the two in the above example are the most important.

Class Hello

The above line containts the Class keyword which is used to define a class. It is followed by the name of the class which in this case is Hello. A class is a program module and most of the time you need to put your programs in classes but you will find out why in a later lesson.

Shared Sub Main()

This line declares the main subprocedure. A subprocedure is a block of code and is used to group parts of a program together. The Shared keyword is something you don't have to worry about now but what it does is allow the subprocedure to be run without instantiating the class. The Sub keyword is used to show that you are defining a subprocedure. Main is the name of the subprocedure and it is where the program starts executing commands from. The two brackets after Main are used for containing parameters but you don't have to worry about that right now.

Console.WriteLine("Hello")

The Console.WriteLine command writes text on the screen. It is followed by brackets which contain the text to write on the screen. All types of text must be put inside double quotes like in the example above because this helps to make sure that it is interpreted by Visual Basic.NET as text instead of as a command.

Console.ReadKey()

Console.ReadKey is a command that waits for the user to press a key before carrying on with the program. If you want to double click on the .exe file of your program to run it instead of running it from a command prompt then you will need this command because the console window immediately disappears after writing Hello if you don't add it in.

End Sub

This line is used to end a subprocedure which in this case is the Main subprocedure. Every time you declare a subprocedure you must remember to use End Sub to end it.

End Class

End Class works in the same way as End Sub but is used for ending a class. Every class must be ended with it.

That is all the code for your first program. Here is what the whole program should look like.

Imports Microsoft.VisualBasic
Imports System

Class Hello

   Shared Sub Main()
      Console.WriteLine("Hello")
      Console.ReadKey()
   End Sub

End Class

You will notice that I have moved some parts of the program a little bit to the right. This is called indenting and is used to make it easier to see the structure of your code. Indenting your code will make it much easier to read and write but you will only start appreciating how important it is when you start writing bigger programs. I have also used empty lines in some places to make the code easier to read. All of this is standard practice so you should get used to it now rather than later.

Compiling the program

To be able to run a program you first need to compile it. When you compile a program, you use a program called a compiler which reads your source code and produces an executable file with a .exe extension. Your source file is a human readable version of what your program should do and the executable is the machine readable program that is actually run by the computer.

To compile your program you need to make sure that you have followed the instructions in the previous lesson. If you have then you will have the .NET Framework SDK installed which includes a Visual Basic.NET compiler called vbc.exe.

VERY IMPORTANT
You will not be able to use the vbc command unless the .NET Framework SDK directory is in your system path. You might find a program on your start menu after installing the .NET Framework SDK that runs a command prompt with the path set properly. If you are unable to find it then your need to add it to your path by yourself. This is a very complex process which can be done in many different ways depending on what operating system you have and what version of the .NET Framework SDK you have. One easy way to get around the problem is to create a .bat file like the following one and run it when you want to compile programs using vbc.

@ECHO OFF
ECHO VB.NET Programming Environment
@SET PATH=%PATH%;C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727
ECHO PATH=%PATH%
CD \vbnet
%ComSpec%

Save the bat file as vbprgenv.bat in your vbnet folder that you created earlier. You might need to change some things in the .bat file to get it to work if you aren't using the 2.0 version of the .NET Framework but in most cases it should work.

You now need to open a command prompt window or run the .bat file from above depending on how you have chosen to do it. Change to the directory in which you saved your source file if you are not already in it. Now make sure that you have saved the source file you created because the compiler can't compile a file that hasn't been saved. Type the following command and press Enter to compile the program.

vbc hello.vb

If you have done everything correctly then it will compile the program without printing any error messages. If you see error messages then you need to go back through the instructions and figure out what you have done wrong. If the program compiled succesfully then an executable file called hello.exe will be created in the same directory as your source file. You can run it be either double clicking on it or by typing in its name on the command prompt and pressing Enter. The program should print Hello on the screen and then wait for you to press a key.
Congratulations on making your first program in Visual Basic.NET.

Using comments

A comment is something you put in a program that is ignored by the compiler but can be used by you to remind yourself of what a part of a program does or just for anything that must not be compiled into the program. You can add a comment to a program using a single quote. The text that you want in the comment must be put after the single quote. Here is an example of how to do it with the comments in bold.

' This is my first program in Visual Basic.NET

Imports Microsoft.VisualBasic
Imports System

Class Hello

   Shared Sub Main()
      Console.WriteLine("Hello") ' Writes Hello on the screen
      Console.ReadKey() ' Waits for the user to press a key
   End Sub

End Class

Practice

To practise what you have learnt, try writing a program that writes things on the screen on multiple lines. After doing that write a program that draws a small tree on the screen using asterisks (*) and use spaces to get the asterisks in the right position.

VB.NET Programming lesson #1 - Getting Started


What is VB.NET?

VB.NET or Visual Basic.NET is a programming language based on Visual Basic and further back than that on the BASIC programming language. It is considered one of the easier programming languages to use. It's ease of use however doesn't make it any less powerful than other programming languages.

Why to learn VB.NET from the command line

VB.NET is usually learnt using a graphical IDE (Integrated Development Environment) such as Visual Studio which is why it is called Visual Basic.NET. There is nothing particularly wrong with learning it from a graphical IDE but there are quite a few advantages to learning VB.NET from the command line. These advantages include:
  • Learning how the proper flow of a program from beginning to end works
  • More of a focus is put on coding rather than the completely simple visual design work
  • It is simple to learn visual programming after learning from the command line but the opposite is not true
  • You will learn how to solve real programming problems rather than simple things like showing a few message boxes and changing the color of buttons
  • You will learn to understand what is going on behind the scenes when a program is compiled in a graphical IDE
  • You won't have to buy an expensive IDE because command line programming is almost always free
  • You will be able to adapt to ASP.NET a lot more easily later on because it processes code in the same way as a console application
  • People who first learnt programming using a graphical IDE tend to not be as good at programming as people who didn't
It is not as easy or as much fun learning from the command line but the easiest way of doing something is often not the best way to do it. If you really must use a graphical IDE then you will still be able to follow these lessons but you will have to figure out how to create console applications in your chosen IDE. It is a good idea to use a graphical IDE such as Visual Studio because it makes it a lot easier to start programming console applications.

Installing the VB.NET compiler

You will need a compiler to create VB.NET programs. If you are using Visual Studio then everything you need will already be installed. If you aren't using Visual Studio then you can use the .NET Framework Software Development Kit. This tutorial uses the Microsoft VB.NET compiler and version 2.0 of the language. Make sure your have installed the .NET Framework Software Development Kit before continuing with the lessons.

You are now ready to start writing your first VB.NET program which you will learn how to do in the next lesson.