-3

我正在尝试创建一个分析文本字符串以查看它是否包含数值的方法。例如,给定以下字符串:

什么是 2 * 2?

我需要确定以下信息:

  • 该字符串包含一个数值:True
  • 它包含的数值是什么:(他们中2的任何人都应该使函数返回 true,我应该将字符串中每个 2 的位置放在一个变量中,例如前 2 的位置 0)

这是我到目前为止的代码:

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

1 回答 1

1

这是一个示例控制台应用程序:

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

如您所见,它传递了字符串“什么是 2 * 2?” 它输出每个数值的位置和值:

8:2

12:2

于 2013-02-20T18:10:00.693 回答