String Functions ASP.NET VB

In this article, I have compiled some common String operations that we encounter while working with the String class. 
All the samples are based on two pre-declared string variables: strOriginal and strModified.
    Dim strOriginal As String = “These functions will come handy”

    Dim strModified As String = String.Empty

1. Iterate a String – You can use the ‘for’ loop or ‘foreach’ loop to iterate through a string. The ‘for’ loop gives you more flexibility over the iteration.

For i As Integer = 0 To strOriginal.Length – 1

            Response.Write(strOriginal(i).ToString())

      Next i

Or

For Each c As Char In strOriginal

            Response.Write(c.ToString())

Next c

2. Split a String – You can split strings using String.Split(). The method takes an array of chars, representing characters to be used as delimiters. In this example, we will be splitting the strOriginal string using ‘space’ as delimiter.

      Dim delim As Char() = {” “c}

      Dim strArr As String() = strOriginal.Split(delim)

      For Each s As String In strArr

            Response.Write(s)

      Next s

3. Extract SubStrings from a String – The String.Substring() retrieves a substring from a string starting from a specified character position. You can also specify the length.

      ‘ only starting position specified

      strModified = strOriginal.Substring(25)

      Response.Write(strModified)

      ‘ starting position and length of string to be extracted specified

      strModified = strOriginal.Substring(20, 3)

      Response.Write(strModified)

4. Create a String array – There are different ways to create a Single Dimensional and Multi Dimensional String arrays. Let us explore some of them:

‘ Single Dimensional String Array

      Dim strArr As String() = New String(2) { “string 1”, “string 2”, “string 3”}

      ‘ Omit Size of Array

      Dim strArr1 As String() = New String() { “string 1”, “string 2”, “string 3” }

      ‘ Omit new keyword

      Dim strArr2 As String() = {“string 1”, “string 2”, “string 3”}

      ‘ Multi Dimensional String Array

      Dim strArr3 As String(,) = New String(1, 1) { { “string 1”, “string 2” }, { “string 3”, “string 4” } }

      ‘ Omit Size of Array

      Dim strArr4 As String(,) = New String(, ) { { “string 1”, “string 2” }, { “string 3”, “string 4” } }

      ‘ Omit new keyword

      Dim strArr5 As String(,) = { { “string 1”, “string 2” }, { “string 3”, “string 4” } }

5. Reverse a String – One of the simplest ways to reverse a string is to use the StrReverse() function.

    Dim strModified As String = StrReverse(strOriginal)

      Response.Write(strModified)

6. Compare Two Strings – You can use the String.Compare() to compare two strings. The third parameter is a Boolean parameter that determines if the search is case sensitive(false) or not(true).

      If (String.Compare(strOriginal, strModified, False)) < 0 Then

            Response.Write(“strOriginal is less than strOriginal1”)

      ElseIf (String.Compare(strOriginal, strModified, False)) > 0 Then

            Response.Write(“strOriginal is more than strOriginal1”)

      ElseIf (String.Compare(strOriginal, strModified, False)) = 0 Then

            Response.Write(“Both strings are equal”)

      End If

7. Convert a String to Byte[] (Byte Array) – The Encoding.GetBytes() encodes all the characters into a sequence of bytes. The method contains six overloads out of which we will be using the Encoding.GetBytes(String).

Dim b As Byte() = Encoding.Unicode.GetBytes(strOriginal)

Note: You can adopt different character encoding schemes (ASCII, Unicode etc.) based on your requirement.

8. Convert Byte[] to String – The Encoding.GetString() decodes a sequence of bytes into a string.

      ‘ Assuming you have a Byte Array byte[] b

      strModified = Encoding.Unicode.GetString(b)

9. Convert a String to Char[](Char Array) – To convert a String to Char Array, use the String.ToCharArray() which copies the characters in the string to a Unicode character array.

      Dim chArr As Char() = strOriginal.ToCharArray()

10. Convert a Char[] to String – A convenient way to convert a character array to string is to use the String constructor which accepts a character array

      strModified = New String(chArr)

11. Test if String is null or Zero Length – A simple way to test if a string is null or empty is to use the String.IsNullOrEmpty(string) which returns a Boolean value.

       Dim check As Boolean = String.IsNullOrEmpty(strOriginal)

Create a String of characters accepted from user –

12. Convert the Case of a String – The String class contains methods to convert a string to lower and upper cases. However, it lacks a method to convert a string to Proper Case/Title Case. Hence we will use the ‘TextInfo’ class to do the same.
      Dim cultureInfo As System.Globalization.CultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture

      Dim textInfo As System.Globalization.TextInfo = cultureInfo.TextInfo

      ‘ Lower Case

      Response.Write(textInfo.ToLower(strOriginal))

      ‘ Upper Case

      Response.Write(textInfo.ToUpper(strOriginal))

      ‘ Proper Case

      Response.Write(textInfo.ToTitleCase(strOriginal))

13. Count the occurrences of words in a String – You can adopt multiple ways to find the occurrence of a word in a string. One of them is to use the String.IndexOf() which is one of the ways of finding the occurrence of the word. In VB.NET, use String.InStr().
Another simple way is to use ‘Count’ property of the Regex.Matches() collection. However this method is slow. We will explore both these methods in the sample.

      ‘ Using IndexOf

       Dim strt As Integer = 0

       Dim cnt As Integer = -1

       Dim idx As Integer = -1

       strOriginal = “She sells sea shells on the sea shore”

       Dim srchString As String = “sea”

       Do While strt <> -1

             strt = strOriginal.IndexOf(srchString, idx + 1)

             cnt += 1

             idx = strt

       Loop

       Response.Write(srchString & ” occurs ” & cnt & ” times”)

      ‘ Using Regular Expression

       Dim rex As System.Text.RegularExpressions.Regex = New System.Text.RegularExpressions.Regex(srchString)

      Dim count As Integer = rex.Matches(strOriginal).Count

      Response.Write(srchString & ” occurs ” & count & ” times”)

14. Insert Characters inside a String – The String.Insert() inserts text at a specified index location of a string. You can insert either a character or a string at a given index location. For eg: We will insert a string “very” at index 26 in string strOriginal.

strModified = strOriginal.Insert(26, “very “)

Response.Write(strModified)

15. Replace characters in a String – The String.Replace() removes characters from a string and replaces them with a new character or string.

      strModified = strOriginal.Replace(“come handy”, “be useful”)

      Response.Write(strModified)

16. Count Words and Characters In a String – You can use Regular Expression to do so as shown below:

      ‘ Count words

      Dim wordColl As System.Text.RegularExpressions.MatchCollection = System.Text.RegularExpressions.Regex.Matches(strOriginal, “[S]+”)

      Response.Write(wordColl.Count.ToString())

      ‘ Count characters. White space is treated as a character

      Dim charColl As System.Text.RegularExpressions.MatchCollection = System.Text.RegularExpressions.Regex.Matches(strOriginal, “.”)

      Response.Write(charColl.Count.ToString())

17. Remove characters in a String – The String.Remove() deletes a specified number of characters beginning at a given location within a string

      ‘ Removes everything beginning at index 25

      strModified = strOriginal.Remove(25)

      Response.Write(strModified)

Or

      ‘ Removes specified number of characters(five) starting at index 20

      strModified = strOriginal.Remove(20,5)

      Response.Write(strModified)

18. Create Date and Time from String – Use the DateTime.Parse() to convert a string representing datetime to its DateTime equivalent. The DateTime.Parse() provides flexibility in terms of adapting strings in various formats.

      strOriginal = “20/06/2011”

      Dim dt As DateTime = DateTime.Parse(strOriginal)

19. Convert String to Base64 – You will have to use the methods in System.Text.Encoding to convert string to Base64. The conversion involves two processes:

a.    Convert string to a byte array

b.    Use the Convert.ToBase64String() method to convert the byte array to a Base64 string

      Dim byt As Byte() = System.Text.Encoding.UTF8.GetBytes(strOriginal)

      ‘ convert the byte array to a Base64 string

      strModified = Convert.ToBase64String(byt)

20. Convert Base64 string to Original String – In the previous example, we converted a string ‘strOriginal’ to Base64 string ‘strModified’. In order to convert a Base64 string back to the original string, use FromBase64String(). The conversion involves two processes:

a.   The FromBase64String() converts the string to a byte array

b.   Use the relevant Encoding method to convert the byte array to a string, in our case UTF8.GetString();

      Dim b As Byte() = Convert.FromBase64String(strModified)

      strOriginal = System.Text.Encoding.UTF8.GetString(b)

21. How to Copy a String – A simple way to copy a string to another is to use the String.Copy(). It works similar to assigning a string to another using the ‘=’ operator.

      strModified = String.Copy(strOriginal)

 
22. Trimming a String – The String.Trim() provides two overloads to remove leading and trailing spaces as well as to remove any unwanted character. Here’s a sample demonstrating the two overloads. Apart from trimming the string, it also removes the “#” character.

      strOriginal = ” Some new string we test ##”

      strModified = strOriginal.Trim().Trim(Char.Parse(“#”))

 

23. Padding a String – The String.PadLeft() or PadRight() pads the string with a character for a given length. The following sample pads the string on the left with 3 *(stars). If nothing is specified, it adds spaces.

      strModified = strOriginal.PadLeft(34,”*”c)

 

24. Create a Delimited String – To create a delimited string out of a string array, use the String.Join()

      Dim strArr As String() = New String(2) { “str1”, “str2”, “str3”}

      Dim strModified As String = String.Join(“;”, strArr)

 

25. Convert String To Integer – In order to convert string to integer, use the Int32.Parse(). The Parse method converts the string representation of a number to its 32-bit signed integer equivalent. If the string contains non-numeric values, it throws an error.

Similarly, you can also convert string to other types using Boolean.Parse(), Double.Parse(), char.Parse() and so on.

      strOriginal = “12345”

      Dim temp As Integer = Int32.Parse(strOriginal)

 

26. Search a String – You can use IndexOf,LastIndexOf, StartsWith, and EndsWithto search a string.

27. Concatenate multiple Strings – To concatenate string variables, you can use the ‘+’ or ‘+=’ operators. You can also use the String.Concat() or String.Format().

      strModified = strOriginal & “12345”

      strModified = String.Concat(strOriginal, “abcd”)

      strModified = String.Format(“{0}{1}”, strOriginal, “xyz”)

However, when performance is important, you should always use the StringBuilder class to concatenate strings.

28. Format a String – The String.Format() enables the string’s content to be determined dynamically at runtime. It accepts placeholders in braces {} whose content is replaced dynamically at runtime as shown below:

      strModified = String.Format(“{0} – is the original string”,strOriginal)

The String.Format() contains 5 overloads which can be studied over here

29. Determine If String Contains Numeric value – To determine if a String contains numeric value, use the Int32.TryParse() method. If the operation is successful, true is returned, else the operation returns a false.

      Dim i As Integer = 0

      strOriginal = “234abc”

      Dim b As Boolean = Int32.TryParse(strOriginal, i)

Note: TryParse also returns false if the numeric value is too large for the type that’s receiving the result.

30. Determine if a String instance starts with a specific string – Use the StartsWith() to determine whether the beginning of a string matches some specified string. The method contains 3 overloads which also contains options to ignore case while checking the string.

      If strOriginal.StartsWith(“THese”,StringComparison.CurrentCultureIgnoreCase) Then

            Response.Write(“true”)

      End If

Since this article contained only a short introduction of each method,
I would suggest you to explore each method in detail using the MSDN documentation. Mastering string operations can save
us a lot of time in projects and improve application performance too.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s