I'm so stuck on this little problem I have, I can't even explain.
I'm writing a program for an assignment,
and I've figured out all of it except for ONE part.
I'm reading a line of data from a txt file, and each line reads "Lastname,firstname phonenumber"
I know how to get the name and phone number from each string, but I can't figure out for the life of me how to extract the firstname without having the phone number attached to it.
I guess if it's any help I'm using visual studio 2006
Please, if anybody knows what I'm talking about and can offer some guidance, that would be great.
Posts
Note: This is not a very robust way of doing this, e.g. in cases of people who have two parts to their first and or last name (e.g. Mark St. John). If you want a robust algorithm, you'll need to look more closely at how the data is arranged on each line, and maybe do a LastIndexOf type of thing.
http://www.thelostworlds.net/
What I'm doing for the last name is this
x=sr.readline
lastName(i) = x.Substring(0, x.IndexOf(","))
This pulls the last name and sticks it into an array.
I've got the phone number with
phoneNbr(i) = x.Substring(x.IndexOf(" ") + 1)
I just can't seem to get that first name out from the middle.
If you can guarantee the formatting of the phone number (IE that the last space in the line is guaranteed to be the break between the first name and phone number), you can use LastIndexOf to split the whole line into two parts - Name and Phone Number. Then you can split the Name using Split() or your existing method.
http://www.thelostworlds.net/
I see. However, I don't think that I'm allowed to use that particular method due to limitations on the assignment.
Thanks though.
If you're going this route why not:
' -- begin code
' start at the character after the comma
' calculate the length of the first name by taking the length of the entire string - length of the last name - length of the phone number - 2 (because there is a comma and a space you need to account for)
firstName(i) = x.Substring(x.IndexOf(",") + 1, (Len(x) - Len(lastName(i)) - Len(phoneNbr(i)) - 2))
' -- end code
I usually use Split or Regular Expressions(if you're using .NET), but that snippet above should fit in with what you've got. This code isn't really robust. It won't handle a crazy name like "Van Huegonaut Esq.,Sir Chesterfield-Welby A8 502-A622234, ext. 234*!" but I understand throwin' in the quick fix just to get something done for most common cases like "Smith,John 555-5555".
edit: Edited twice to fix parenthesis. I'm worthless without intellisense
edited again upon realization that VB uses ' for comments instead of //
YES!!! YOU ARE AWESOME!!!
Thanks so much, you've saved me some SERIOUS brain melting!