Question

I am attempting to create a method which analyzes a string of text to see if it contains a numeric value. For instance, given the following string:

What is 2 * 2?

I need to determine the following information:

  • The string contains a numeric value: True
  • What is the numeric value that it contains: 2 (anyone of them should make the function return true and I should put the position of each of the 2's in the string in a variable such as position 0 for the first 2)

Here is the code I have so far:

Public Function InQuestion(question As String) As Boolean
    ' Possible substring operations using the position of the number in the string?
End Function
Was it helpful?

Solution

Here's an example console application:

Module Module1
    Sub Main()
        Dim results As List(Of NumericValue) = GetNumericValues("What is 2 * 2?")
        For Each i As NumericValue In results
            Console.WriteLine("{0}: {1}", i.Position, i.Value)
        Next
        Console.ReadKey()
    End Sub

    Public Class NumericValue
        Public Sub New(value As Decimal, position As Integer)
            Me.Value = value
            Me.Position = position
        End Sub

        Public Property Value As Decimal
        Public Property Position As Integer
    End Class

    Public Function GetNumericValues(data As String) As List(Of NumericValue)
        Dim values As New List(Of NumericValue)()
        Dim wordDelimiters() As Char = New Char() {" "c, "*"c, "?"c}
        Dim position As Integer = 0
        For Each word As String In data.Split(wordDelimiters, StringSplitOptions.None)
            Dim value As Decimal
            If Decimal.TryParse(word, value) Then
                values.Add(New NumericValue(value, position))
            End If
            position += word.Length + 1
        Next
        Return values
    End Function
End Module

As you can see, it passes the string `"What is 2 * 2?" and it outputs the positions and values of each numeric value:

8: 2

12: 2

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top