peterthottam
Member
- Joined
- Oct 20, 2012
- Messages
- 6
- Programming Experience
- Beginner
How to use IndexOf & Substring to separate and sum string of comma separate numbers?
I've been trying to get this to work but am having problems with the loops and counters. Basically -- NOT using arrays or split functions -- I need to write a function that takes one string made of numbers separated by comma and then have the function return the total of all the separate numbers (number of entered comma separated values is fungible depending on how many values the user enters into the textbox). E.g., textbox1 string is: 10,11,12 --> Total =33. Or, 1,33,121,3,55 ---> Total = 213.
Below is my code so far. Thanks in advance!
I've been trying to get this to work but am having problems with the loops and counters. Basically -- NOT using arrays or split functions -- I need to write a function that takes one string made of numbers separated by comma and then have the function return the total of all the separate numbers (number of entered comma separated values is fungible depending on how many values the user enters into the textbox). E.g., textbox1 string is: 10,11,12 --> Total =33. Or, 1,33,121,3,55 ---> Total = 213.
Below is my code so far. Thanks in advance!
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim s, showVal As String Dim Total, x, length As Integer Dim comma1Position As Integer 'this is used to get the index of the first comma position Dim oldcomma1Position As Integer 'dummy register variable Dim commaCount As Integer = 0 s = TextBox1.Text length = s.Length x = 0 comma1Position = 0 oldcomma1Position = 0 commaCount = 0 Total = 0 Do While s.IndexOf(",",comma1Position) <> -1 oldcomma1Position = comma1Position x = s.IndexOf(",") comma1Position = s.IndexOf(",", comma1Position) Total = Total + CInt(s.Substring(oldcomma1Position, comma1Position)) commaCount = commaCount + 1 Loop showVal = " The Total is: " & Total MessageBox.Show(showVal) End Sub End Class
Last edited by a moderator: