• Welcome to Overclockers Forums! Join us to reply in threads, receive reduced ads, and to customize your site experience!

OMG I'm Going Cross Eyed

Overclockers is supported by our readers. When you click a link to make a purchase, we may earn a commission. Learn More.

Bjm2587

Member
Joined
Aug 12, 2008
Ok I'm trying to program in vb.net and I need some help trying to find a space in a string that has more than one space. I want to be able to find both spaces using the indexof method. Here's my code so far. Basically the program will turn the string "Will Smith" to "Smith, Will" But I noticed when I type in a name with a middle initial or middle name "Will J Smith" I would get "J Smith, Will" And I want to be able to find that second space when its there and apply a code that would produce "Smith, Will J" When there is a second space.

(stay with me this kinda gets confusing)

I feel like I'm really close and then it blows up on me. So the way I see it is this: firstname equals the full name up until the first space. Then lastname equals the full name after the first space. then I assign the secondspace to equal the first space in the last name. Then I assign the middle name to equal whats in the last name up until the first space of the last name (second space for the full text entry) and then to finish it off I reassign lastname to be whatevers after the second space. As you can see I have the label show me the value of the second space and its always zero when it should be reading 1. Why isnt it reading 1 when it should be? After thinking about this so hard I'm surprised I havn't gone cross eyed. Save me from insanity, thanks.



Code:
Private Sub btnApply_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnApply.Click

        Dim fullname As String
        Dim indexspace As Integer
        Dim firstname As String
        Dim lastname As String
        Dim indexSecondSpace As Integer
        Dim middlename As String

        fullname = txtName.Text.Trim
        fullname = fullname.Replace(".", "")
        txtName.Text = fullname

        indexspace = fullname.IndexOf(" ")

        firstname = fullname.Substring(0, indexspace)

        lastname = fullname.Substring(indexspace)
        indexSecondSpace = lastname.IndexOf(" ")
        middlename = lastname.Substring(0, indexSecondSpace)
        lastname = fullname.Substring(indexSecondSpace)






        If indexspace < 0 Then
            MessageBox.Show("Please enter your first name followed by a space and your last name into the text box", "Error")
            spaceCheckOk = False
            txtName.Focus()
        Else
            spaceCheckOk = True
        End If
        

        If spaceCheckOk = True Then
            lblName.Text = indexSecondSpace.ToString
        End If



    End Sub
 
Code:
Private Sub btnApply_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnApply.Click

        Dim fullname As String
        Dim indexspace As Integer
        Dim firstname As String
        Dim lastname As String
        Dim indexSecondSpace As Integer  //get rid of this
        Dim middlename As String  //get rid of this

        fullname = txtName.Text.Trim
        fullname = fullname.Replace(".", "")
        txtName.Text = fullname

       /**
       * I'm not fluent in vb.net but here you would use a for loop to traverse the string
       **/
        indexspace=-1;
        For i=0;i<fullname.Length;i++
           if fullname.getCharAt(i)==" "
             indexspace = i
           end if
        end for
        
        firstname = fullname.Substring(0,indexspace)
        lastname = fullname.Substring(indexspace)





        If indexspace < 0 Then
            MessageBox.Show("Please enter your first name followed by a space and your last name into the text box", "Error")
            spaceCheckOk = False
            txtName.Focus()
        Else
            spaceCheckOk = True
        End If
        

        If spaceCheckOk = True Then
            lblName.Text = indexSecondSpace.ToString
        End If



    End Sub

The way you are going about this is a little bit convoluted. Try searching for the last space in the name(the function will still have an upper bound O(n)) and splitting it there. This way you won't have to have a separate sub function in case there is a middle initial.
 
Last edited:
I dont know how to search for more than one space. using indexof will only show the value for the first space so if the string contained john J doe the value of indexspace will report 4 and not even go on to the next space which would be 6. That's how I got started with all that confusing code above. I figured if the last name is going to show the middle name-space-last name for the last name I could just split that the same way I split the first name from the last name but it wasnt as simple as I thought... So how would I search for more than one space?
 
Not familar with VB, but this is probably your issue - apparently substring in VB takes a starting index and grabs a set number of characters starting at that index (yah Google).

So the issue is lastname = fullname.Substring(indexspace)
Change it to lastname = fullname.Substring(indexspace+1)

With your code, the values of the variables you're using with input "Will_J_Smith" (_ in place of spaces) would be:
Code:
indexspace = 4
firstname = "Will"
lastname = "_J_Smith"
indexSecondSpace = 0
middlename = don't know what VB does with this call, probably returns empty string
lastname = "_J_Smith"
See the problem?

Also, google reveals that VB does have a LastIndexOf method as well.

Lesson: Know what the methods you're calling do. Documentation is good :)
Also, running through the code line by line with a debugger would also help sort out these problems in the future - you'll be able to see what is assigned to yoru variables through each line and so you can pinpoint where something unexpected happened - in this case, at lastname = fullname.Substring(indexspace+1)
 
Last edited:
You know I never stopped to realize that the reason indexSecondSpace was coming up with zero is because there is a space before and after the middle name. So it's doing what it's supposed to be doing which is reading off the first space. _J_Smith. So I would want it to find the second space which in this case would be the value 2. Thanks for pointing that out. I just don't know the proper syntax to get it what I want it to do. I keep trying to type c commands lol.

Update: good god I'm so close. I just need to figure out how to make the last name only show whats after the indexSecondSpace. I tried lastname.remove (0,2) But that will only work when the middle name is an initial and of course doesnt work with the full midle name. Help

Code:
If spaceCheckOk = True Then

            firstname = fullname.Substring(0, indexspace)
            lastname = fullname.Substring(indexspace).Trim
            indexSecondSpace = lastname.IndexOf(" ")

            If indexSecondSpace < 0 Then
                firstname = fullname.Substring(0, indexspace)
                lastname = fullname.Substring(indexspace)

                lblName.Text = lastname & ", " & firstname
            Else
                lastname = lastname.Substring(indexspace).Trim
                middlename = lastname.Substring(0, indexSecondSpace)
                lblName.Text = lastname & ", " & firstname & " " & middlename
            End If

        End If
 
Last edited:
WAHOOO! Got it! It probably isnt the most elegant but it works whether the middle name is a letter or a full word. I wonder if I can check if the middle name is a full word and then only show the first letter of the middle name lol

Now all I really gotta do is figure out how to convert them first letters to uppercase. Ideas?

Code:
        If spaceCheckOk = True Then

            firstname = fullname.Substring(0, indexspace)
            lastname = fullname.Substring(indexspace).Trim
            indexSecondSpace = lastname.IndexOf(" ")

            If indexSecondSpace < 0 Then
                firstname = fullname.Substring(0, indexspace)
                lastname = fullname.Substring(indexspace)

                lblName.Text = lastname & ", " & firstname
            Else
                lastname = fullname.Substring(indexspace).Trim
                middlename = lastname.Substring(0, indexSecondSpace)
                lastname = lastname.Substring(indexSecondSpace)
                lblName.Text = lastname & ", " & firstname & " " & middlename
            End If

        End If
 
can anyone tell me how to take a name entered in a text box and convert only the first letter of each name to upper and then convert the rest to lower.

Ex: "john doe" --> "John Doe"

"jAkE sMiTh" --> "Jake Smith"

Thanks.
 
Hmmm... Is this a school assignment? Might have just been easier to split the whole thing into an array and piece the name back together as you see fit. I'm a C# guy, but you should be able to get the gist of it:

Code:
if (spaceCheckOK)
{
    // Split the full name into an arry... this will create a string array for each 
    // space in the fullName string
    string[] nameArray = fullName.Split(new char[] { ' ' });
    
    if (nameArray.Length > 2)  // if there are 3 array elements present
    {
        // Assuming the third member of the array is the last name, we set the 
        // "last" index first and have the first and second follow

        // string.Format() is a nice tool, since, we can create a template 
        // string, and the method will fill in the placeholders with whatever 
        // you define
        lblFirstName.Text = string.Format("{0}, {1} {2}", nameArray[2], nameArray[0], nameArray[1]);
    }
    else
    {
        lblFirstName.Text = string.Format("{0}, {1}", nameArray[1], nameArray[0]);
    }
}

I'm aware that you're coding in VB.NET and not C#. The beautiful thing, though, is that you can use the same implementation that I have, if you wanted to. VB.NET has it's own string.Format() and string.Split() methods. Very cool stuff that MS has done with the framework. :)
 
I would suggest using the ToLower() function which converts the entire string to lower case and then using ToUpper() on the first letter and on every letter after a space.
 
Hmmm... Is this a school assignment? Might have just been easier to split the whole thing into an array and piece the name back together as you see fit. I'm a C# guy, but you should be able to get the gist of it:

Code:
if (spaceCheckOK)
{
    // Split the full name into an arry... this will create a string array for each 
    // space in the fullName string
    string[] nameArray = fullName.Split(new char[] { ' ' });
    
    if (nameArray.Length > 2)  // if there are 3 array elements present
    {
        // Assuming the third member of the array is the last name, we set the 
        // "last" index first and have the first and second follow

        // string.Format() is a nice tool, since, we can create a template 
        // string, and the method will fill in the placeholders with whatever 
        // you define
        lblFirstName.Text = string.Format("{0}, {1} {2}", nameArray[2], nameArray[0], nameArray[1]);
    }
    else
    {
        lblFirstName.Text = string.Format("{0}, {1}", nameArray[1], nameArray[0]);
    }
}

I'm aware that you're coding in VB.NET and not C#. The beautiful thing, though, is that you can use the same implementation that I have, if you wanted to. VB.NET has it's own string.Format() and string.Split() methods. Very cool stuff that MS has done with the framework. :)

Or you can just search the string backwards, and tokenize by the first space it comes across. You guys are making this too hard :shrug:

Bjm: ToLower everything, then tokenize by space, and for each entry in your array, take the first character and ToUpper it.

EDIT: somehow competely missed twig's post.
 
Just remember that simple = better. It may not seem like a big deal now but once you work on projects with a lot of different parts it is so much easier.
 
Hey everyone I appreciate the help but this all might be a little too advanced for me.

teddythetwig: Yes I thought about what you said I just need help putting that into code...
I tried firstname.ToLower()
firstname.Substring(0, 1).ToUpper()

I dont see why that doesnt work... I converted everything to lowercase then I used substring to single out the first charecter to uppercase but nothing it all stays lower case
 
Damn I'm on a roll. I got it. Thanks everyone, even if I didn't use your code examples it got me thinking outside the box and that was the motivation I needed.

Code:
/assignment
 
Hey everyone I appreciate the help but this all might be a little too advanced for me.

teddythetwig: Yes I thought about what you said I just need help putting that into code...
I tried firstname.ToLower()
firstname.Substring(0, 1).ToUpper()

I dont see why that doesnt work... I converted everything to lowercase then I used substring to single out the first charecter to uppercase but nothing it all stays lower case

Gratz on figuring it out man! Just for future reference though, ToUpper() returns another string so firstname.Substring(0, 1).ToUpper() will just return the first letter as an uppercase.
 
And, just to make things worse, strings in DotNet are immutable (they can't be changed). So any time you make a change to a string, DotNet has to create a whole new string somewhere else in memory and move the first one into it. For one or two changes, no big deal. But if you're going to go letter by letter through a string changing stuff, or you're going to keep adding a letter to the end of a string, it's best to use a StringBuilder. I think it's part of the System.Text namespace.
 
Back