Petefic
Petefic

Reputation: 677

VB.NET: Convert string containing "Lastname, Firstname" to "Firstname Lastname"

I'm trying to convert a string that contains someones name as "Last, First" to "First Last".

This is how I am doing it now:

name = name.Trim
name = name.Substring(name.IndexOf(",") + 1, name.Length) & " " & name.Substring(0, name.IndexOf(",") - 1)

When I do this I get the following error:

ArgumentOutOfRangeException was unhandled

Index and length must refer to a location within the string

Parameter name: length

Can someone explain why I am getting this error and how I should be doing this?

Upvotes: 2

Views: 5701

Answers (5)

JicaJuice
JicaJuice

Reputation: 1

This would work keeping to the posters format.

Name = "Doe,John"
Name = Replace(Name.Substring(Name.IndexOf(","), Name.Length - Name.IndexOf(",")) & " " & Name.Substring(0, Name.IndexOf(",")), ",", "")

Result Name = "John Doe"

Upvotes: 0

Kale Krunch Monster
Kale Krunch Monster

Reputation: 1

If you're using the Unix command line--like the terminal on a Mac--you can do it like this:

Let's say that you have a file containing your last-comma-space-first type names like this:

Last1, First1
Last2, First2
Last3, First3

OK, now let's save it as last_comma_space_first.txt. At this point you can use this command I came up with for your particular problem:

sed -E 's/([A-Za-z0-9]+), ([A-Za-z0-9]+)/\2 \1/g' last_comma_space_first.txt > first_space_last.txt

--->>> Scroll --->>>

You're done! Now, go check that first_space_last.txt file! ^_^ You should get the following:

First1 Last1
First2 Last2
First3 Last3

Tell your friends... Or don't...

Upvotes: 0

Sleiman Jneidi
Sleiman Jneidi

Reputation: 23339

simply ,you only need to split the string

Dim originalName As String = "Last,First"
Dim parts = name.Split(","C)
Dim name As String = parts(1) & "  " & parts(0)

Upvotes: 1

Jonathan S.
Jonathan S.

Reputation: 2228

The second parameter for String.Substring is the length of the substring, not the end position. For this reason, you're always going to go out of bounds if you do str.Substring(n, str.Length) with n > 0 (which would be the whole point of a substring).

You need to subtract name.IndexOf(",") + 1 from name.Length in your first substring. Or just split the string, as the others have suggested.

Upvotes: 1

John Woo
John Woo

Reputation: 263813

You are getting error on this:

name.Substring(name.IndexOf(",") + 1, name.Length)

name.Length should have subtracted with the length of the string before the comma.

The best way for that is to split the string.

Dim oFullname as string = "Last, First"
Dim oStr() as string = oFullname.split(","c)
oFullname = oStr(1).trim & " " & oStr(0).trim
MsgBox (oFullname)

Upvotes: 6

Related Questions