如何拆分字符串以获取字符串中的最后一个词或 2 个词,但不知道字符数或结束词数?

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?

比标题更具体...这里是要使用的字符串的一个示例:"You have received 25 dollars from John Doe"我需要 nameDonated 来获取名字 John 或 John Doe,具体取决于字符串是否有名字或名字和姓氏。下面是我在字符串中显示 John Doe 的代码,但它只获取 John 而不是全名 John Doe。我正在使用 Visual Basic 2010。有人可以帮忙吗?

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."

因为它始终采用相同的格式,"You have received x dollars from y",您可以根据该格式拆分字符串。

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)

有时最简单的答案是最好的。使用您的原始代码,将名称分配更改为

Dim nameDonated As String = fields(6) & If(fields.Length = 8, " " & fields(7), "")