4 Leave Cover
4 Leave Cover

Reputation: 1276

Sum numbers within string

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

Answers (3)

user1023602
user1023602

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

Fjodr
Fjodr

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

Tim Schmelter
Tim Schmelter

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

Related Questions