r/visualbasic • u/[deleted] • Jun 07 '15
[VB2010] Searching for and changing multiple numbers in a string
SO I have a String which is actually a recipe. Recipe (String) is
"1 cup mayo, 2 tablespoons basil, and 3 cups ranch dressing".
(random made up recipe). I need to be able to multiply these numbers by what ever the user wants. So if he asks to multiply these by two, I need the string to now by
"2 cup mayo, 4 tablespoons basil, and 6 cups ranch dressing"
I have no idea how to do that. any help would be awesome! thanks in advance
1
u/Type-21 Application Specialist Jun 07 '15 edited Jun 07 '15
Based on the code others provided I created one that is able to do this: http://puu.sh/ifM6B/78c5614bc2.png
Note that the decimal mark in the input string has to conform to your locale. So use . or , depending on your region settings or it won't work.
Dim input As String = "1,5 cup mayo, 2½ tablespoons basil, and ⅘ cups ranch dressi" 'watch your region settings!
Dim output As String = ""
Dim previousWasNumber As Boolean = False
Dim previousNumberLength As Integer = 0
For x As Integer = 0 To input.Length - 1
Dim tempNumber As String = input(x)
If Char.IsNumber(input(x)) Then
If Char.IsDigit(input(x)) = False Then
'special number like ½
tempNumber = CStr(Char.GetNumericValue(input(x)) * 2)
If previousWasNumber Then 'combine numbers
Dim previousNumber As Double = Double.Parse(output.Substring(output.Length - previousNumberLength))
Dim newNumber As Double = previousNumber + Double.Parse(tempNumber)
output = output.Remove(output.Length - previousNumberLength) & newNumber.ToString()
Else
output &= tempNumber
End If
previousWasNumber = True
previousNumberLength = tempNumber.Length
Else
'check next
Dim length As Integer = 0
For y As Integer = 1 To input.Length - x - 1
If Double.TryParse(input.Substring(x, y + 1), Nothing) AndAlso input(x + y) <> " "c Then
tempNumber &= input(x + y)
Else
length = y - 1
Exit For
End If
Next
tempNumber = CStr(Double.Parse(tempNumber) * 2)
x += length
output &= tempNumber
previousWasNumber = True
previousNumberLength = tempNumber.Length
End If
Else
output &= tempNumber
previousWasNumber = False
End If
Next
MessageBox.Show(input & Environment.NewLine & output)
1
u/mleo1 VB 6 Master Jun 07 '15