Darryl Darryl - 1 year ago 79
Vb.net Question

How do I split a string to get the last word or 2 words in a string but do not know the number of characters or ending words?

To be more specific than the title... here is one example of a string to use: "You have received 25 dollars from John Doe" I need nameDonated to get just the name John or John Doe depending on if the string has first name or first and last name. Below is the code I have showing John Doe in the string but it only gets John and not the full name John Doe. I am using Visual Basic 2010. Can anyone help?

Dim myString As String = "You have received 25 dollars from John Doe"

Dim fields() As String = myString.Split(" ")

Dim numberDollars As String = fields(3).Substring(0)

Dim nameDonated As String = fields(6).Substring(0)

' outputs John donated 25 dollars
TextBox1.Text = nameDonated & " donated " & numberDollars & " dollars."

Answer Source

Since it's always in the same format, "You have received x dollars from y", you can split the string based on that format.

Dim myString As String = "You have received 25 dollars from John Doe"
' split into {"You have received 25 dollars", "John Doe"}
Dim mySplitString1 As String() = myString.Split(New String() {" from "}, 0)
' and take the second item which has the name
Dim donorName As String = mySplitString1(1)
' then split the first item into {"You", "have", "received", "25", "dollars"}
Dim mySplitString2 As String() = mySplitString1(0).Split(" ")
' and take the fourth item which has the amount
Dim dollarAmount As Single = Single.Parse(mySplitString2(3))

TextBox1.Text = String.Format("{0} donated {1:0} dollars", donorName, dollarAmount)

Sometimes the simplest answer is the best. Using your original code, change the name assignment to

Dim nameDonated As String = fields(6) & If(fields.Length = 8, " " & fields(7), "")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download