JoeS JoeS - 5 months ago 8
Vb.net Question

How to get a value for each character in a string in VB

I am creating a program where the code needs to get a value from each character in a string (that can vary in length). Such as a name, an example, Tony, where T = 1, O = 4, N = 7, Y = 3. This has to add to a total. I have tried loops but only getting 1 as an output, even if there isn't a character that has a value in the string.

Dim FNTL As Integer = Nothing

Dim FN = FN_TBX.Text
For Each A, J, S As Char In FN_TBX.Text
FNTL = +8
Next

Dim FNTLstr
FNTLstr = Convert.ToString(FNTL)
LN_TBX.Text = FNTL


FN_TBX is the textbox input
FN is the textbox input
FNTL is the total
FNstr is the total in string format

Some characters have the same value such as above, A, J, S are = to 8. The integer conversion is to display the total to a text box.

Answer

The logic is not entirely clear. Maybe you should have a Dictionary(Of Char, Int32) to get a value for each char and a fallback-value if it's not defined.

Here is an example with a dictionary which is declared as class field:

Dim _charValue As New Dictionary(Of Char, Int32) From
{
        {"t"c, 1}, {"T"c, 1},
        {"o"c, 4}, {"O"c, 4},
        {"n"c, 7}, {"N"c, 7},
        {"y"c, 3}, {"Y"c, 3},
        {"a"c, 8}, {"A"c, 8},
        {"j"c, 8}, {"J"c, 8},
        {"s"c, 8}, {"S"c, 8}
}

Now you can calculate the sum in your method, for example with a simple loop:

Dim sum as Int32 = 0
For Each c As Char In FN_TBX.Text
    Dim charValue = 0
    If Not _charValue.TryGetValue(c, charValue)
        charValue = 1 ' fallback value
    End If
    sum += charValue 
Next
LN_TBX.Text = sum.ToString()