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.

0 comments:

Post a Comment