Question How to use IndexOf & Substring to separate and sum string of comma separate numbers?

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!

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:
Have you debugged your code? I'll wager not. Reading code is all well and good but, particularly with code that loops and branches, is often not enough. You need to watch your code in action. Place a breakpoint at the top of the code using F9. When execution hits that line it will break, allowing you to examine the state. You can step through the code line by line using F10. At each line, determine the current state and the expected state after the next step. Perform the step and then determine the current state. If it doesn't match the expected state then you've found an issue. Fix the issue, rinse and repeat.
 
Thx. I have been debugging using Visual Studio 2010. I've cleaned up the code but am still having loop and total aggregation problems (string to integer). Not sure what I'm doing wrong.

Here is my current code:


    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
        Dim number As String
        Total = 0


        Do While x <> -1
            oldcomma1Position = comma1Position
            x = s.IndexOf(",")
            comma1Position = s.IndexOf(",", (oldcomma1Position + 1))
            number = s.Substring(oldcomma1Position, x)
            Total = Total + CInt(number)


            commaCount = commaCount + 1




        Loop
 
Last edited by a moderator:
Edit: Post deleted.

Just remembered OP needs to use indexOf and substring..

My suggestion did not use indexOf


Peter if you step through your loop again you will see what the problem is.. the code tries to pass a comma as an integer.. you are using an old comma position as a starting point for your substring which is wrong because no matter how long your string will be, it will always start with a comma. You are also calling a useless integer value as the length for your substring.. x never changes, however the length of the numbers do change so your string length needs to be set dynamically to reflect this as it did in your first example..

Couple of random thoughts as well.. Is this your code or did you copy something from someone/where and try to modify it? Why are you creating commaCount variable when it seems to serve no purpose? If Do While x <> -1 is the loop condition, then why is there no way to exit the loop when x = s.indexOf(",") and the 's' string never changes?
 
Last edited:
You may not be sure what you're doing wrong but, if you've followed my advice, you know where the issue is and what the symptoms are. If you've debugged properly then you should be able to say that at line A the initial state is B, the expected state is C and the final state is D, where D does not match C. If you can't say that then you haven't debugged properly. If you've written the code then you must know what you expect to happen at each line.
 
By the way, I had already added formatting tags to your first post and now I've done it for your second as well. Please do it yourself in future posts so that we can read your code snippets comfortably.
 
Ok. I'm going to continue to work on. Its my own code. The leftover conditions are from past logic walkthroughs (I will clean up).

What I have currently is below. Your above points re the comma breakdown are legit but for the life of me, I can't figure out how to clean this up properly. I keep going in circles. Fyi, this is only my second programming class (my first was Java over the summer) and I plan to take Advanced VB later next year.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim s, storageString, showVal As String
Dim Total, i, 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
i = 0
comma1Position = 0
oldcomma1Position = 0
commaCount = 0
Dim number As String
Total = 0


Do While s.IndexOf(",", comma1Position) <> -1




comma1Position = s.IndexOf(",", oldcomma1Position)
number = s.Substring(oldcomma1Position, comma1Position)
Total = Total + CInt(number)
oldcomma1Position = comma1Position
commaCount = commaCount + 1
i = i + 1
Loop
showVal = " The Sum Total of the Comma Separated Values You Entered Is: " & Total


MessageBox.Show(showVal)




End Sub
 
Hi,

Without giving you the answer there are three major points that you need to work on and figure out:-

1) Look at your oldComma1position variable. You do two things with this variable. Firstly you set it to the POSITION of the last comma found. You then use this variable as your start point in your call to SubString. So after the first iteration of the loop your returned SubString will always start with the character "," therefore you will always get a conversion error when adding to your Total variable. Consider what you need to do to oldComma1position to get it to work.

2) Again, look at your SubString routine, once you have solved point 1 above you use SubString(oldComma1position, comma1Position). Here your commaPosition variable is being used to define the length of the string to be returned. This is not correct so what do you need to do here to sort this?

3) Once point 2 is solved consider what will happen at the end of the loop. Since your last number in the string will not have a comma after it are you going to pick it up in the loop by looking for the comma character? What do you need to do at the end of the loop to accommodate this?

Good luck and hope the steer helps.

Cheers,

Ian
 
Points 1 and 2 addressed. I believe. Thank you.
I have revised code below and can get a 'penultimate' total. My problem is the length of the s string near the end of the loop going negative. More specifically, the last number in the string does not have a comma after it. How am I you going to pick it up in the loop by looking for the comma character? What do I need to do at the end of the loop to accommodate this? Please let me know if you have any suggestions.

- Pete (T: 310.497.7255)



Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim s, storageString, showVal As String
Dim Total, i, 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
i = 0
comma1Position = 0
oldcomma1Position = 0
commaCount = 0
Dim number As String
Total = 0

Do While s.IndexOf(",", comma1Position) <> -1

comma1Position = s.IndexOf(",", oldcomma1Position)
number = s.Substring(oldcomma1Position, (comma1Position - oldcomma1Position))
Total = Total + CInt(number)
MessageBox.Show(Total)
oldcomma1Position = comma1Position + 1
commaCount = commaCount + 1
i = i + 1
Loop
showVal = Total & " The Sum Total of the Comma Separated Values You Entered Is: " & Total & "The number of Commas is: " & commaCount



Hi,

Without giving you the answer there are three major points that you need to work on and figure out:-

1) Look at your oldComma1position variable. You do two things with this variable. Firstly you set it to the POSITION of the last comma found. You then use this variable as your start point in your call to SubString. So after the first iteration of the loop your returned SubString will always start with the character "," therefore you will always get a conversion error when adding to your Total variable. Consider what you need to do to oldComma1position to get it to work.

2) Again, look at your SubString routine, once you have solved point 1 above you use SubString(oldComma1position, comma1Position). Here your commaPosition variable is being used to define the length of the string to be returned. This is not correct so what do you need to do here to sort this?

3) Once point 2 is solved consider what will happen at the end of the loop. Since your last number in the string will not have a comma after it are you going to pick it up in the loop by looking for the comma character? What do you need to do at the end of the loop to accommodate this?

Good luck and hope the steer helps.

Cheers,

Ian
 
Hi Pete,

That looks better and you can now see that it loops successfully. You already have the necessary logic principals to get the last number in the string but you just need to use a couple of different properties of the string collection. Have a look into the .Length and .LastIndexOf properties and I am sure you will be able to work out how to get the last number.

Just a couple of other notes for you. Consider the redundancies in your code that you can get rid off and also consider what would happen if there was only one number in the string with NO commas in the string? What would be the result then and what should be the result?

Hope that helps.

Cheers,

Ian
 
Back
Top