Get Initials from a String in VB.NET
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 SubPublic 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.