要比标题更具体...这是一个使用字符串的示例:“您已从John Doe收到25美元”我需要nameDonated才能获得John或John Doe的名字,具体取决于字符串是否有名字或名字和姓氏。下面是我在字符串中显示John Doe的代码,但仅获取John而不是全名John Doe。我正在使用Visual Basic2010。有人可以帮忙吗?
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."
由于它始终采用相同的格式,即“您已经从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), "")
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句