如何分割字符串以获得字符串中的最后一个单词或两个单词,但不知道字符或结束单词的数量



要比标题更具体…这里有一个字符串的例子:"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), "")

最新更新