WorldofASP.NET : ASP.NET Directory, Tutorial, Hosting, and Source Code
You are 1 of 243 users


Get Initials from a String in VB.NET

Blogger : ASP.NET Blogs
All posts : All posts by ASP.NET Blogs
Category : ASP.NET
Blogged date : 2006 Oct 16

So I've been in way over my head lately, converting a massive spaghetti-code Classic ASP application to .NET 2.0. Recently my client supplied with one of those Intro-to-Programming exam questions that was kinda fun, so I thought I'd post the answer here.

He needed to pull a person's initials out of a string, and he needed to handle either "LastName, FirstName" or "FirstName LastName".

Now, you can't just strip out all the capital letters, because Scottish guys like me will throw a wrench in that logic. So the easies way to do it is to split the string with a space character, and grab the first letter from each resulting string.

So here is the result, with a few test cases called from a test webpage for good measure. Hope you like:

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Response.Write(GetInitialsFromString("Robert McLaws") & "<br />")
        Response.Write(GetInitialsFromString("Bill Gates") & "<br />")
        Response.Write(GetInitialsFromString("Robert W. McLaws") & "<br />")
        Response.Write(GetInitialsFromString("McLaws, Robert") & "<br />")
        Response.Write(GetInitialsFromString("McLaws, Robert W.") & "<br />")
    End Sub

    Public Function GetInitialsFromString(ByVal fullName As String) As String
        If fullName.Contains(",") Then
            fullName = NormalizeName(fullName)
        End If
        Dim nameArray As String() = fullName.Split(" ")
        Dim initials As String = String.Empty
        For Each name As String In nameArray
            initials += name.Chars(0)
        Next
        Return initials.ToUpper()
    End Function

    Public Function NormalizeName(ByVal fullName As String) As String
        Dim name As String() = fullName.Split(",")
        Return String.Format("{0} {1}", Trim(name(1)), Trim(name(0)))
    End Function

So if anyone ever needs to do this... there you go :). It's also a useful function for person-related .NET objects, so you can grab the initials by calling PersonObject.Initials instead of having to do it manually.

Share this post: Email it! | bookmark it! | digg it! | reddit!

Read comments or post a reply to : Get Initials from a String in VB.NET
Page 1763 of 1924
Next | Last

.NET News Categories








Legend : - Within 3 Days - Within 6 Days - Within 9 Days

Home | Add Resources | Sponsored Listings | Advertise with Us | SiteMap 1 | SiteMap 2 | Link To Us | Contact Us
© 2002-2008 Worldofasp.net ASP.NET Directory, Hosting and Tutorials | All rights reserved
Our Partners : ASP.NET Web Hosting | Windows Web Hosting | ASP.NET Hosting | Phone Card | PHP Directory | Bangkok Hotels |Calling Card