比标题更具体......这里是一个使用字符串的例子:“你收到了John Doe的25美元”我需要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."
答案 0 :(得分:1)
由于它始终采用相同的格式,“您已从y收到x美元”,因此您可以根据该格式拆分字符串。
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), "")