Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Second part - indexof 1

Status
Not open for further replies.

brews

Technical User
Dec 12, 2007
194
US
Looking to use indexof in a string that contains Lastname, Firstname. if this is used
Code:
                Dim sSearch As String = frmSearch.lstDisplay.SelectedItem.ToString
                Dim sLast As String = sSearch.Substring(0, sSearch.IndexOf(",")).Trim
it returns Lastname. However, it is the next step that is a puzzle to me as to how to pick up the Firstname excluding the comma space after the comma.

Any help is appreciated. thanks.
 
Here is what I came up with using VB6 stuff
Code:
                Dim sSearch As String = frmSearch.lstDisplay.SelectedItem.ToString
                Dim iLast As Integer = sSearch.Length
                Dim sLast As String = sSearch.Substring(0, sSearch.IndexOf(",")).Trim
                Dim sSpace As String = sSearch.IndexOf(" ")
                Dim sFirst As String = Microsoft.VisualBasic.Right$(sSearch, iLast - sSpace)
It works but hopefully, there is something that I can use without referring to vb6.

Thanks.
 
Hi, there as many ways.

Code:
        Dim sSearch As String = "Lastname, FirstName"
        Dim sLast As String = sSearch.Split(",")(1).Trim


Note: I am searching for the "," only, not including the space, just in case it is omited. If you search for ", " witch is comma+space then you can omit the .Trim property. I would use it by the way so i can trim any potential space at the end or more than one spaces at the begining, like "Lastname, Firstname".

Note also that if there is no search pattern, the split wont create the array and thus the 2nd item in the array (index 1) will cause an exception. You can use try/catch or other ways...
 
Note also that if there is no search pattern, the split wont create the array

Need to rephrase. It was correct in my head but there was an output problem :)

If the search fails (so the split wont actually split anything) then the created array will have one item only - the whole "Lastname, FirstName". Accessing the 2nd item of the array will cause an "index outside the bounds" exception.
 
Here is another trickier with regural expressions.

Code:
Imports System.Text.RegularExpressions  ' Put out of class

        Dim sSearch As String = "Lastn  ame, Firstname"
        Dim sLast As String = Regex.Matches(sSearch, "[A-Za-z]+$").Item(0).Value
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top