One of the biggest differences between ‘classic’ ASP and Visual BASIC / VBScript and the .NET versions is in the way in which strings are represented and manipulated within the language. In this tutorial we’ll take a look at the ways in which .NET strings are handled, and also present some useful functions to make things a little more like ‘ASP Classic’.
In ASP.NET strings are represented as objects, and like any object they have properties and methods associated with them. This is why such functions as trim() appear at first glance to be missing from ASP.NET. They’re there, but as methods on the string object, rather than as functions. One advantage offered by this approach is that it becomes impossible to apply a function like Trim to, for example, a numeric variable as in .NET the equivalent of the trim function is only available on string variables!
Take a look at the following listing; this features a few basic string methods.
<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<%
Dim sString As String = "Hello World!"
Response.Write("The string is: " & sString)
Response.Write("<br />")
Response.Write("The length of the string is: " & sString.Length)
Response.Write("<br />")
Response.Write("The Upper Case version of the string is: " & sString.ToUpper)
Response.Write("<br />")
Response.Write("The lower case version of the string is: " & sString.ToLower)
Response.Write("<br />")
%>
</div>
</form>
</body>
</html>
If you take a look at the intellisense available in Visual Web Developer or Visual Studio, when you type the ‘.’ after the name of a string variable, you’ll see a range of methods and properties available. Many of these allow us to reproduce the functionality that we’re used to in classical ASP, and to demonstrate this we’ve created a VB.NET class that contains a series of functions that reproduce such functions as Mid, Left(), Right(), InStr().
The class code is listed below. It should be saved to a VB.NET class file in the App_Code folder of your site. By making each function in the class shared, they can be called from anywhere in the web site without you having to create a separate instance of the class. This type of class where existing functionality is ‘wrapped up’ to make it available in a slightly different form is called a wrapper class. Our wrapper class here ‘wraps up’ the functionality of some existing .NET methods which could, of course, be called within the pages without needing the class.
The class wraps up the following .NET string methods and makes them available as functions via the class.
| .NET String Method | Usage |
| .Length | Applied to a string returns the number of characters in the string. E.g. string.Length |
| .SubString | Returns a section of a string. We use it as follows:SubString(start, length) – returns ‘length’ characters starting at position ‘start’
Substring(start) – returns all characters from ‘start’ to end of the string. * Remember the first character has a starting index of 0 |
| Replace | This method replaces a section of a string with another string. |
| IndexOf | This is similar to InStr function in that it returns the first position at which a specified string can be found in a string:sStringSearched.IndexOf(sTargetString) will return the position of sTargetString in sStringSearched |
Imports Microsoft.VisualBasic
Public Class stringHandler
'================================================================================
'
' Class to contain string handling functions
'
'================================================================================
Public Shared Function Left(ByVal str As String, ByVal index As Integer) As String
' Returns the leftmost 'index' characters of string 'str'
Return str.Substring(0, index)
End Function
Public Shared Function Right(ByVal str As String, ByVal index As Integer) As String
' Returns the rightmost 'index' characters of string 'str'
Return str.Substring(str.Length - index)
End Function
Public Shared Function Trim(ByVal str As String, Optional ByRef chArray() As Char = Nothing) As String
' Returns string 'str' with whitespace removed from start and end.
' If the chArray character array is populated then in addition removes
' any characters in the character array from start and end.
Try
' This will throw an exception if the array has not
' been passed in.
Return str.Trim(chArray)
Catch ex As Exception
Return str.Trim
End Try
End Function
Public Shared Function Instr(ByVal sStringSearched As String, ByVal sTargetString As String) As Integer
' Returns the position of the first occurence of sTargetString in sStringSearched
Dim iIndex As Integer
iIndex = sStringSearched.IndexOf(sTargetString)
Return iIndex
End Function
Public Shared Function Mid(ByVal sString As String, ByVal iStart As Integer, ByVal iLength As Integer) As String
' Returns a section of the string.
Return sString.Substring(iStart, iLength)
End Function
Public Shared Function Replace(ByVal sString As String, ByVal sFind As String, ByVal sReplaceWith As String) As String
' Replaces a substring, sFind, within a string with sReplaceWith
Return sString.Replace(sFind, sReplaceWith)
End Function
End Class
The functions in the above class are all demonstrated in the following web page.
<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<%
' Ensure that the VB.NET file containing the stringHandler class
' is in the App_Code folder for this site
Dim sString As String = " Hello World! "
Response.Write("The string is #" + sString + "#")
Response.Write("<br />")
' Now use the basic trim function
Response.Write("The trimmed string is #" + stringHandler.Trim(sString) + "#")
Response.Write("<br />")
' Now trim with extra character. Note that adding the specified character
' ! in the character array will remove that character AS WELL AS WHITESPACE.
' You can also add additional characters to the character array and remove those as
' well – e.g. Dim chArr1() As Char = {"!","$"} would remove trailing dollar signs
' and exclamation marks.
Dim chArr1() As Char = {"!"}
Response.Write("The string trimmed for spaces and ! is #" + stringHandler.Trim(sString, chArr1) + "#")
Response.Write("<br />")
' Now left and right
sString = "Hello World!"
Response.Write("New String is " + sString)
Response.Write("<br />")
Response.Write("Left most 4 characters " + stringHandler.Left(sString, 4))
Response.Write("<br />")
Response.Write("Right most 4 characters " + stringHandler.Right(sString, 4))
Response.Write("<br />")
' Now InStr
Response.Write("Position of word 'Goodbye' " & stringHandler.Instr(sString, "Goodbye"))
Response.Write("<br />")
Response.Write("Position of word 'World' " & stringHandler.Instr(sString, "World"))
Response.Write("<br />")
' Now Mid - 4 characters starting at location 4
Response.Write("4 characters starting at position 4 " & stringHandler.Mid(sString, 4, 4))
Response.Write("<br />")
' Now Replace
Response.Write("Replace World with Earth " & stringHandler.Replace(sString, "World", "Earth"))
Response.Write("<br />")
%>
</div>
</form>
</body>
</html>
A final useful method available for string manipulation is the split method. This allows you to chop a string up in to pieces based on delimiters. There are a number of applications in which this facility is invaluable such as parsing a comma-separated file, for example. The example shown below uses the split method to split a sentence in to separate words.
<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<%
Dim sString As String = "This is a sentence to split"
Dim sWords() As String = sString.Split(" ")
Dim i As Integer
For i = 0 To sWords.Length - 1
Response.Write(sWords(i) + "<br />")
Next
%>
</div>
</form>
</body>
</html>
Get the best asp web hosting provider now and save 30%
Plug and play ASP membership script that integrates with PayPal to let you charge recurring membership fees.