2015-04-28 89 views
0
Dim strOrig = "192/8' 33/5' 76/24' 17/12'" 

大家好,我想獲取每個數字之前的「/」。輸出將是318. 關於如何實現它,我能想到的是:字符串內的總數字

1.通過查找「間距」作爲每個段的終點並將它們放入數組中,分離所有段。例如。 (0)192/8,(1)33/5,(2)76/24 etc ...

2.通過循環數組,查找斜槓「/」並獲取之前的數字和sum直到循環結束。例如。 (0)192,(1)33,(2)76等...

我想知道我的方法是否值得我努力,因爲我想了解更多有效的方法。謝謝大家。

+0

是這始終是格式化? (例如數字/數字) – nevra

+0

由於後面有單引號,我會說它是(數字/字符串)。 –

回答

6

你可以使用LINQ:

Dim strOrig = "192/8' 33/5' 76/24' 17/12'" 
Dim numbers = From word In strOrig.Split() 
       Let number = word.Split("/"c).First().Trim().TryGetInt32() 
       Where number.HasValue 
       Select number.Value 

Dim sum As Int32 = numbers.Sum() ' 318 

我用下面的擴展爲一個字符串嘗試,解析到Integer?

<Extension()> 
Public Function TryGetInt32(Str As String) As Nullable(Of Int32) 
    If Str Is Nothing Then Return Nothing 
    Dim num As Int32 
    If Int32.TryParse(Str, num) Then Return num 
    Return Nothing 
End Function 
+0

(不要忘記那個LINQ中的VB.NET行續綴下劃線) – valverij

+1

@valverij:VS 2010不需要 –

+0

在'Integer'上選擇'Int32'有什麼特別的理由嗎? – asawyer

0

最簡單的我能想到的。

Dim lst As List(Of String) = strOrig.Split("/").ToList 

    lst.RemoveAt(lst.Count - 1) 
    lst.Sum(Function(x) Convert.ToUInt16(x)) 
+1

最簡單的方法不起作用? –

+0

有關拆分的一點工作,是的。 – Fjodr

1

Regex救援:

Dim strOrig As String = "192/8' 33/5' 76/24' 17/12'" 

    Dim sum as Integer = (From m As Match In Regex.Matches(strOrig, "(?<number>\d+?)/") 
          Select Convert.ToInt32(m.Groups("number").Value) 
         ).Sum()