Link Round-Up for 9/6/07Site News for 9/2/07 through 9/8/07

3 More Useful VB.NET String Functions

September 7th, 2007

3 string functions: String To Stream, Compare and Word CountA few weeks ago I wrote an article called 3 Handy VB.NET String Functions You Can Use and it’s been one of the more popular articles on this site. So, I thought I’d follow it up with another article on string functions. Hopefully, you will find this one helpful as well.

Converting a String To a Stream

There are a number of objects in .NET that require a Stream as a parameter and many of these won’t accept a string as a parameter. Many new-to-VB.NET programmers have run into this situation and been frustrated. The trick here is to place the string into a MemoryStream. This is simply a stream object that uses memory as a storage device rather than a disk.

However, you will also need to specify the type of encoding for your string. In most cases, an ordinary string will use ASCII encoding but you may also run into Unicode strings. Therefore it’s important for you to know the type of encoding you should use in your application. The encoding methods are in the System.Text namespace.

Once you know the encoding method, you will want to use the GetBytes function to convert the target string into a byte array.

OK, here’s the example function and it can be reduced down to only one line:

Dim MemStream As New IO.MemoryStream(System.Text.Encoding.ASCII.GetBytes(MyStringData))

Now that you have the string converted to the stream, perhaps you want to know how to get a string back from the MemoryStream. ToString only returns the name of the object, so what do you do? Remember we converted the string to an array of bytes for the stream so we will need to simply copy this array back to a string, like so:

MyStringData = System.Text.Encoding.ASCII.GetString(MemStream.ToArray))

Remember to use the same encoding method for both functions! Also, bear in mind when you’re using streams that you need to properly close and dispose of streams in order to release resources. MemoryStream misuse can result in your application having a memory leak so make sure you do this.

Using String.Compare

It’s common to compare strings using the classic equal (=) or not equal (<>) operators but often the case of the letters being inconsistant has caused programmers to resort to functions like this in VB6:

If UCase(txtHomeAddress.Text) = UCase(txtShippingAddress.Text) Then

However, in VB.NET, we can use the String.Compare function to handle this.

If String.Compare(txtHomeAddress.Text, txtShippingAddress.Text, True) = 0 Then

This built-in String class function takes two string arguments, either of which can be Nothing, and returns less than zero (-1) is the first string is less than the second, zero (0) if they’re equal, and greater than zero (1) if the first string is greater. Overloads allow you to ignore case, as in the example above. You can also use comparison methods outside of the default one as well using overloads.

Another powerful overload option on this function is the ability to compare parts of a string. In this example, we will see if the beginning 3 characters of our first string match the 3 ending characters of our second string:

If String.Compare(Puzzle1, 0, Puzzle2, Puzzle2.Length - 3, 3, True) = 0 Then

For those of you transitioning to VB.NET, remember, strings in VB.NET are zero based, not one based like they were in VB6.

Getting The Word Count

A common way to get the number of words in a string in VB is to use the Split command and then get the count of the resulting array. This is rather inefficient since it requires allocating an array and so forth. It is easier and faster to use a regular expression to do this, as seen in this example function:

Public Function WordCount(ByVal value As String) As Integer
    Return System.Text.RegularExpressions.Regex.Matches(value, "(((^s*)*S+s+)|(S+))").Count()
End Function

This regular expression matches any white-space character and the function returns the number that were found. It will consider 2 white-space characters together as one. Regular expressions, while rather obtuse, are very powerful and you should consider them for string parsing or comparison functions not directly provided within the .NET Framework. I do recommend wrappering them in functions for easy correction, modification and reuse.

I hope you’ve found this article helpful. Let me know by leaving a comment with any thoughts or questions you might have.

Share This Article: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • Reddit
  • StumbleUpon
  • Technorati
  • DotNetKicks
  • DZone

Entry Filed under: Code Examples, Tip Sheets

Rate This Article:

Not That GoodCould Be BetterOKGoodGreat (No Ratings Yet)
Loading ... Loading ...

2 Comments Add your own

  • 1. Jacky  |  May 28th, 2008 at 12:41 am

    seems the WordCount Function is not working properly

  • 2. mafas  |  August 3rd, 2008 at 12:06 am

    i want code to count the string

    example, string is mafas
    the mafas have how many m,a,f,s?

    pls reply my question.

Leave a Comment


Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed

Visit Me At My New Site, Programming In C#

Most Popular Articles

Highest Rated Articles


Most Recent Articles


 Subscribe in a reader

To subscribe by e-mail
Enter your address here

Delivered by FeedBurner

VB Opportunities