# How do I convert each element of a string array to an integer? (VB)

• ### Question

•  For my current task I have to read in an 8 digit card number using an array. I have declared my array as this at the beginning of my code: ``Dim LoyaltyCardDigits(8) As Integer`` The reason I declared this as an integer is because I need to carry out calculations on these array elements after it has been read in. I am reading in 8 characters from a textbox and then assigning these characters to a variable. ``CardNumber = txtCardNumber.Text`` and I am assigning these characters to the array elements; but this is my problem that I am stuck on. ``````Private Sub btnSubmitDetails_Click(sender As Object, e As EventArgs) Handles btnSubmitDetails.Click For Counter = 1 To 8 LoyaltyCardDigits(Counter) = Mid(CardNumber, Counter, 1) Next Counter`````` So to conclude I would like a solution to convert the array elements from string to integer so I can perform calculations. I have no need to worry about validation as I have already coded it. As I am extremely new to VB I would prefer if any help was as simplified as possible but I will obviously accept anything that works.
Saturday, December 2, 2017 2:40 PM

• You code with the next adjustment seems to work too:

For Counter = 1 To 8
LoyaltyCardDigits(Counter) = CInt(Mid(CardNumber, Counter, 1))
Next Counter

Though there is an unused array element ‘LoyaltyCardDigits(0)’, but this is not a major issue.

What difficulties do you experience?

• Marked as answer by Saturday, December 2, 2017 7:36 PM
Saturday, December 2, 2017 3:11 PM

### All replies

•  For my current task I have to read in an 8 digit card number using an array. I have declared my array as this at the beginning of my code: ``Dim LoyaltyCardDigits(8) As Integer`` The reason I declared this as an integer is because I need to carry out calculations on these array elements after it has been read in. I am reading in 8 characters from a textbox and then assigning these characters to a variable. ``CardNumber = txtCardNumber.Text`` and I am assigning these characters to the array elements; but this is my problem that I am stuck on. ``````Private Sub btnSubmitDetails_Click(sender As Object, e As EventArgs) Handles btnSubmitDetails.Click For Counter = 1 To 8 LoyaltyCardDigits(Counter) = Mid(CardNumber, Counter, 1) Next Counter`````` So to conclude I would like a solution to convert the array elements from string to integer so I can perform calculations. I have no need to worry about validation as I have already coded it. As I am extremely new to VB I would prefer if any help was as simplified as possible but I will obviously accept anything that works.

Hi

Of the many ways to do this, my usual approach is to use a function to do the conversion.

Doing it this way, lets you either loop through a collection of strings, or, do the conversion for a single item (such as a TextBox input)

Such a function could be:

```    Function GetInteger(s As String) As Integer
Dim v As Integer = 0
If Integer.TryParse(s, v) Then Return v
Return 0
End Function```

NOTE: the function will always return a valid integer, but, if the input string is not a string representation of a number then it will return ZERO.

Regards Les, Livingston, Scotland

• Edited by Saturday, December 2, 2017 2:54 PM
Saturday, December 2, 2017 2:52 PM
• Jarlath,

Here's a function that you can use:

```    Private Function _
GetNumbers(ByVal text() As String) As IEnumerable(Of Integer)

If text IsNot Nothing AndAlso text.Length > 0 Then
Dim tempList As New List(Of Integer)

For Each s As String In text
If Integer.TryParse(s, New Integer) Then
End If
Next

Return tempList
Else
Return Nothing
End If

End Function```

"A problem well stated is a problem half solved.” - Charles F. Kettering

• Edited by Saturday, December 2, 2017 3:14 PM ...added screenshot
Saturday, December 2, 2017 3:06 PM
• You code with the next adjustment seems to work too:

For Counter = 1 To 8
LoyaltyCardDigits(Counter) = CInt(Mid(CardNumber, Counter, 1))
Next Counter

Though there is an unused array element ‘LoyaltyCardDigits(0)’, but this is not a major issue.

What difficulties do you experience?

• Marked as answer by Saturday, December 2, 2017 7:36 PM
Saturday, December 2, 2017 3:11 PM
• Hi

Thanks for replying. I actually realised my mistake with the array indexes. Instead of-

Dim LoyaltyCardDigits(8) As Integer

I now have

Dim LoyaltyCardDigits(7) As Integer

Further info:

1. Now that my array contains 8 integers, I need to remove the 8th and store it as a check digit.
2. I then need to reverse the order of the remaining 7 digits (i.e. 1234567 becomes 7654321)
3. I then need to multiply the 1st, 3rd, 5th and 7th array index by 2.
4. If any of these multiplications are greater than 9, I need to subtract 9 from that result.
5. I then need to add the 7 digits and the CheckDigit.
6. If the result is divisible by 10, the card is valid.

I am happy with the theory behind all of these; but I have implemented your code and now instead of a error message appearing my program simply doesn't produce any ouput (the ouput is text in a label)

Saturday, December 2, 2017 4:03 PM
• You can use Array.ConvertAll to do this. I use a inline predicate rather than call a function as shown in the demo for the documentation for Array.ConvertAll, either way is fine.

```Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim someValues As String() = {"Karen", "12", "Payne", "4", Nothing, "8"}

Dim Values() As Integer = Array.ConvertAll(someValues, New Converter(Of String, Integer)(
Function(input)
Dim output As Integer = 0
'
' If the value can't be converted to a integer
' we send back 0 for that value
'
Integer.TryParse(input, output)
Return output
End Function))

For Each item As Integer In Values
Console.WriteLine(item)
Next
End Sub```

Output

```0
12
0
4
0
8```

A slight tweak to see if all values are valid in the initial array

```If Not Array.ConvertAll(someValues, Function(s) If(Integer.TryParse(s, value), value, -2345)).Any(Function(x) x = -2345) Then
Dim Values() As Integer = Array.ConvertAll(someValues, New Converter(Of String, Integer)(
Function(input)
Dim output As Integer = 0
'
' If the value can't be converted to a integer
' we send back 0 for that value
'
Integer.TryParse(input, output)
Return output
End Function))

For Each item As Integer In Values
Console.WriteLine(item)
Next

End If```

Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
VB Forums - moderator

Saturday, December 2, 2017 4:12 PM
• Hi

Thanks for replying. I actually realised my mistake with the array indexes. Instead of-

Dim LoyaltyCardDigits(8) As Integer

I now have

Dim LoyaltyCardDigits(7) As Integer

Further info:

1. Now that my array contains 8 integers, I need to remove the 8th and store it as a check digit.
2. I then need to reverse the order of the remaining 7 digits (i.e. 1234567 becomes 7654321)
3. I then need to multiply the 1st, 3rd, 5th and 7th array index by 2.
4. If any of these multiplications are greater than 9, I need to subtract 9 from that result.
5. I then need to add the 7 digits and the CheckDigit.
6. If the result is divisible by 10, the card is valid.

I am happy with the theory behind all of these; but I have implemented your code and now instead of a error message appearing my program simply doesn't produce any ouput (the ouput is text in a label)

Hi

Which code have you 'implemented'?

You would need to provide your code (all of it) before any further help could be provided.

Regards Les, Livingston, Scotland

Saturday, December 2, 2017 4:18 PM
• Here is start for remembering the last value, remove it, reversal of array

```Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim someValues As String() = {"11", "12", "49", "4", "8", "33", "24", "1"}
Dim Values() As Integer = Array.ConvertAll(someValues, New Converter(Of String, Integer)(
Function(input)
Dim output As Integer = 0
'
' If the value can't be converted to a integer
' we send back 0 for that value
'
Integer.TryParse(input, output)
Return output
End Function))

' remember last element before removal
Dim keeper = Values.Last
Console.WriteLine(\$"Remeber: {keeper} ")
ReDim Preserve Values(Values.Length - 2)

Array.Reverse(Values)

For Each item As Integer In Values
Console.WriteLine(item)
Next
End Sub```

Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
VB Forums - moderator

Saturday, December 2, 2017 4:31 PM
• ```Public Class Form1
Dim CustomerName, CustomerPostCode, CardNumber As String
Dim CheckDigit, Number, PointPosition, SpacePosition As Integer
Dim LoyaltyCardDigits(7) As Integer
Dim Total As Decimal
Dim ExpiryDate, CurrentDate As Date
Dim DivisibleBy10 As Boolean

'As soon as program loads, set the CurrentDate variable equal to the date on the computer. Hide result label.
CurrentDate = Date.Today
lblDisplayResult.Visible = False
End Sub

'Validation of CustomerName: There must be a space between the User's first name and surname; there musn't be any numbers in the name; the box musn't be left blank.  If any of these criteria are not met the data is rejected.
Private Sub txtCustomerName_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles txtCustomerName.Validating

'Check if the user has left a space between their first and last names.
SpacePosition = InStr(txtCustomerName.Text, " ")

'If the quit button is not clicked then carry out the validation.
If btnQuit.Focused <> True Then
'Validation of CustomerName: check if it is a full name, not numeric or blank.
If txtCustomerName.Focused = True Then
If IsNumeric(txtCustomerName.Text) = True Then
txtCustomerName.Text = " "
txtCustomerName.Focus()
ElseIf SpacePosition = 0 Or txtCustomerName.Text = "" Then
txtCustomerName.Text = " "
txtCustomerName.Focus()
Else
CustomerName = txtCustomerName.Text
End If
End If
End If
End Sub

'This procedure prevents the user from entering any erroneous ASCII values (i.e. ASCII values that are not 1,2,3,4,5,6,7,8 or 9) in the CardNumber textbox.
Private Sub txtCardNumber_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtCardNumber.KeyPress

If Not (Asc(e.KeyChar) = 8) Then
Dim AllowedNumbers As String = "123456789"
If Not AllowedNumbers.Contains(e.KeyChar.ToString) Then
e.Handled = True
End If
End If
End Sub

'Valdation of CardNumber: The card number must be 8 digits in length. If it is more or less than that, the input is rejected.
Private Sub txtCardNumber_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles txtCardNumber.Validating

'If the quit button is not clicked then carry out the validation.
If btnQuit.Focused <> True Then
If txtCardNumber.Focused = True Then
If Len(txtCardNumber.Text) <> 8 Then
MsgBox("The card number you have entered is not 8 numbers long, please try again.")
txtCardNumber.Text = " "
txtCardNumber.Focus()
Else
CardNumber = txtCardNumber.Text
End If
End If
End If
End Sub

'Validation of CustomerPostCode: The PostCode must be 7 characters in length; the first two charcters are letters, followed by 3 numbers and finished by 2 letters. If this format is not matched, the input is rejected.
Private Sub txtCustomerPostCode_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles txtCustomerPostCode.Validating

'If the quit button is not clicked then carry out the validation.
If btnQuit.Focused <> True Then
If txtCustomerPostCode.Focused = True Then
If Len(txtCustomerPostCode.Text) <> 7 Then
MsgBox("This is not the valid length of a postcode (7 characters long)")
txtCustomerPostCode.Text = " "
txtCustomerPostCode.Focus()
Else
CustomerPostCode = UCase(txtCustomerPostCode.Text)
End If
End If
End If
End Sub

'Validation of ExpiryDate: the value entered into the DateTimePicker by the user is checked agaisnt the current date. If the ExpiryDate is less than the CurrentDate, the card is rejected.
Private Sub dtpExpiryDate_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dtpExpiryDate.ValueChanged

'If the quit button is not clicked then carry out the validation.
If btnQuit.Focused <> True Then
If dtpExpiryDate.Value < CurrentDate Then
End If
End If
End Sub

'This procedure will call the other necessary procdures that will be used to generate the output.
Private Sub ProcessNumbers()

ReverseNumbers()

MultiplyOdds()

CalculateTotal()

DivideTotalBy10()

End Sub
'This procedure takes the values of the LoyaltyCardDigits array and reverses them ie. 12345678 will become 87654321
Private Sub ReverseNumbers()

For i As Integer = 6 To 0
Number = 0
LoyaltyCardDigits(i) = LoyaltyCardDigits(Number)
Number = Number + 1
Next i

End Sub
'This procdure takes the even values of the reversed LoyaltyCardDigits array (which is really the 1st, 3rd, 5th and 7th card number)  and multiplies them by 2.
Private Sub MultiplyOdds()

For i As Integer = 0 To 6 Step 2
LoyaltyCardDigits(i) = (LoyaltyCardDigits(i) * 2)
Next i

'Also, if any of these multiplied products are greater than 9, subtract 9 from them.
If LoyaltyCardDigits(0) > 9 Then
LoyaltyCardDigits(0) = LoyaltyCardDigits(0) - 9
End If
If LoyaltyCardDigits(2) > 9 Then
LoyaltyCardDigits(2) = LoyaltyCardDigits(2) - 9
End If
If LoyaltyCardDigits(4) > 9 Then
LoyaltyCardDigits(4) = LoyaltyCardDigits(4) - 9
End If
If LoyaltyCardDigits(6) > 9 Then
LoyaltyCardDigits(6) = LoyaltyCardDigits(6) - 9
End If

End Sub
'This procedure adds up the multiplied odd digits and the remaining even ones. Once that has been done, the check digit is then added on.
Private Sub CalculateTotal()

For i As Integer = 0 To 6
Total = LoyaltyCardDigits(i) + Total
Next i

Total = Total + CheckDigit

End Sub
'This function is used to decide if the total 'CanBeDividedBy10' by checking if the divided total contains a decimal point or not. If the divided result contains a decimal point, it is not divisble by 10.
Function CanBeDividedBy10(ByVal Total As Integer) As Boolean
If PointPosition = 0 Then
Return DivisibleBy10 = True
Else
Return DivisibleBy10 = False
End If
End Function
'This procedure firstly divides the total by 10. Then it calls the CanBeDividedBy10 function to determine if the loyalty card number is valid or not.
Private Sub DivideTotalBy10()

Total = Total / 10
PointPosition = InStr(Total, ".")
DivisibleBy10 = CanBeDividedBy10(Total)
If DivisibleBy10 = True Then
lblDisplayResult.Visible = True
lblDisplayResult.Text = CustomerName & vbNewLine & CustomerPostCode & vbNewLine & "This card is valid and eligible for a 10% discount."
Else
lblDisplayResult.Visible = True
lblDisplayResult.Text = CustomerName & vbNewLine & CustomerPostCode & vbNewLine & "Sorry, this card is invalid."
End If

End Sub
'This click event assigns the values of the CardNumber variable to each LoyaltyCardDigits array element.
Private Sub btnSubmitDetails_Click(sender As Object, e As EventArgs) Handles btnSubmitDetails.Click

If Len(CardNumber) = 8 Then
For i As Integer = 0 To 7
LoyaltyCardDigits(i) = CInt(CardNumber.Substring(i, 1))
Next i

'Next assign the CheckDigit variable to the 7th LoyalyCardDigits array element.
CheckDigit = LoyaltyCardDigits(7)
ProcessNumbers()
End If

End Sub

'When btnQuit is clicked, end the program.
Private Sub btnQuit_Click(sender As Object, e As EventArgs) Handles btnQuit.Click
End
End Sub

End Class```

Thank you for your patience. This is my entire program, feel free to edit.

P.S I am having problems mainly revolving around my LoyaltyCardDigits array even after changing it a few times and trying different resolutions.

Saturday, December 2, 2017 5:39 PM
• Hi

Please show rall the steps you want to perform on an example user input of the CardNumbers. As an example, use (say) 23456611 as the input and show the operation for each step and show the intermediate values step by step..

Regards Les, Livingston, Scotland

Sunday, December 3, 2017 12:54 PM