3 Reasons Why VB6 is DeadJonathan Coulton’s Code Monkey

3 Handy VB.NET String Functions You Can Use

July 19th, 2007

3 Quick ExamplesWhile the .NET String object offers a lot of functionality, there are still some things that we can add to it. In this article, we’ll look at these 3 useful string functions:

  1. Shorten a string with an ellipsis in the middle
  2. Reverse the contents of a string
  3. Use XOR to do simple string encryption/decryption

1. Shorten a string that contains a file path with ellipsis

It is common to see file paths shortened by having an ellipsis in the middle, like so

c:\records\data\jon...\report_xyz.pdf

If you need to implement this kind of functionality it isn’t too hard to code it yourself but you can also use a built in
.NET function to do it as well as seen here:

Function ShortenPathString(ByVal pathString As String, ByVal targetWidth As Integer, _
                           ByVal targetFont As Drawing.Font) As String
    TextRenderer.MeasureText(pathString, targetFont, New Drawing.Size(targetWidth, 0), TextFormatFlags.PathEllipsis Or TextFormatFlags.ModifyString)
    Return pathString
End Function

In this example we use the MeasureText method of the TextRenderer object to build an appropriately sized string. The path, as a string, is passed in along with the width and font so that the correct sizing can be determined. The PathEllipsis tell the routine to place the ellipsis in the middle of a validly constructed path string.

The limitation of this routine and the underlying TextRenderer method is that it only works with a properly constructed path/filename and not with other strings.

Here is a method I came up with for doing this for any string.

Function ShortenStringWithEllipsis(ByVal targetString As String, ByVal targetWidth As Integer, _
                                   ByVal targetFont As Drawing.Font) As String
    Dim ReturnString As String
    Dim StringWidth As Integer = TextRenderer.MeasureText(targetString, targetFont).Width
    If StringWidth <= targetWidth OrElse targetString.Length <= 10 Then
        ReturnString = targetString
    Else
        ReturnString = String.Concat(targetString.Substring(0, (targetString.Length  2)), Chr(1), targetString.Substring((targetString.Length  2)))
        Dim StringParts() As String
        Do While TextRenderer.MeasureText(ReturnString, targetFont).Width > targetWidth
            StringParts = Split(ReturnString, Chr(1))
            StringParts(0) = StringParts(0).Substring(0, StringParts(0).Length - 1)
            StringParts(1) = StringParts(1).Substring(1)
            ReturnString = String.Concat(StringParts(0), Chr(1), StringParts(1))
        Loop
        If ReturnString.Contains(Chr(1)) Then
            ReturnString = ReturnString.Replace(Chr(1), “…”)
        End If
    End If
    Return ReturnString
End Function

In this code, we check the length of the string first and if it is OK we return the string unmodified but if it is longer we split the string in half and loop, removing 1 character from each end, until it fits. I used a ASCII character 1 to serve as a placekeeper for the ellipsis since it is unlikely to be in visible text. After the string is shortened enough the ellipsis is replaced and the short string is returned.

2. Reverse the contents of a string

This simple code example shows a quick way to reverse a string using the Array.Reverse method:

Function ReverseString(ByVal targetString As String) As String
    Dim Characters() As Char = targetString.ToCharArray
    Array.Reverse(Characters)
    Return Characters
End Function

3. Use XOR to do simple string encryption/decryption

In this example, XOR is used to do a simple encryption/decryption of a string. The string is encrypted by using the bitwise XOR operator on every character using the contents of a mask or key string. To decrypt it, the mask is applied the same way to the encrypted string.

Function XorString(ByVal targetString As String, ByVal maskValue As String) As String
    Dim Index As Integer = 0
    Dim ReturnValue As String = ""
    For Each CharValue As Char In targetString.ToCharArray
        ReturnValue = String.Concat(ReturnValue, Chr(Asc(CharValue) Xor Asc(maskValue.Substring(Index, 1))))
        Index = (Index + 1) Mod maskValue.Length
    Next
    Return ReturnValue
End Function

This encryption method is quite vulnerable to being broken so it should not be used for any non-trivial situation. It can be made more secure by using it in conjuction with a Vernam Cipher

You can download the sample code here: 3 String Functions Demo

If you have better or different ways of doing these functions or if you have any questions about them please feel free to leave me a comment.

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

Entry Filed under: Code Examples


Rate This Article:

Not That GoodCould Be BetterOKGoodGreat (3 votes, average: 4.33 out of 5)
Loading ... Loading ...

4 Comments Add your own

  • 1. fanxing7273  |  September 10th, 2007 at 8:07 pm

    i like your site!

  • 2. jfrankcarr  |  September 10th, 2007 at 9:17 pm

    Thanks.

    I hope you find it helpful.

  • 3. Susan  |  July 3rd, 2008 at 11:59 pm

    > Vernam Cipher or XorString()

    Why not just simply use 1 of the several VERY powerful, built-in, encryption methods that are already a part of vb.net????

    1 line of code.

  • 4. softclean  |  February 28th, 2009 at 3:38 pm

    A note with the 1st function:

    Although the pathString is being passed as value, the value passed to the function is also modified. Eg:


    For Each f As String In openDialog.FileNames
    ' Add the f to a position in aStringList collection
    aStringList.Add(f)
    ' ... and now to our listbox, with a shorten look :)
    lstImages.Items.Add(ShortenPathString(f, lstImages.Width, lstImages.Font))
    Next

    At the final execution, f it’s modified in the lstImages Listbox, and also in the aStringList colllection!

Leave a Comment

Required

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

Categories

Most Recent Articles

Feeds

 Subscribe in a reader

To subscribe by e-mail
Enter your address here

Delivered by FeedBurner

VB Opportunities

Archives