Reputation: 1276
Dim strOrig = "192/8' 33/5' 76/24' 17/12'"
Hi all, I want to obtain every number before the "/". The output will be 318. Regarding how to achieve it, what I can think of is:
1.Split all the segment by looking for 'spacing' as end point for each segment and put them into an array. E.g. (0)192/8, (1)33/5, (2)76/24 etc...
2.By looping the array, look for the slash "/" and get the number before it and sum it until loop end. E.g. (0)192, (1)33, (2)76 etc...
I would like to know if my method was worth the effort as I would like to learn any MORE effective ways than this. Thanks all.
Upvotes: 0
Views: 2486
Reputation:
Regex to the rescue:
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()
Upvotes: 1
Reputation: 923
The most simple I can think of.
Dim lst As List(Of String) = strOrig.Split("/").ToList
lst.RemoveAt(lst.Count - 1)
lst.Sum(Function(x) Convert.ToUInt16(x))
Upvotes: 0
Reputation: 460098
You can use 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
I've used following extension to try-parse a string to 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
Upvotes: 7