Hi. I'm trying to create a program where a user can type in a 5 digit number and my program has to add the first and third digit numbers together. I'm having difficulty getting the program to work. I'm using Visual Basic 2005. Any advice?
Numbers in Strings
Collapse
X
-
Tags: None
-
Every string object has a method called "Chars()" that allows you to pull out characters at specific locations. In your case, you're using a textbox, so it will be [Object_Name].Text.Chars()
For example:
[CODE=vbnet]dim intFirst as Short = Convert.toInt16 (txtNumber.Text .Chars(0))
dim intSecond as Short = Convert.toInt16 (txtNumber.Text .Chars(2))
dim intAnswer as Short = intFirst + intSecond
MessageBox.Show (intAnswer.ToSt ring)[/CODE]
Line by Line:
[CODE=vbnet]dim intFirst as Short = Convert.toInt16 (txtNumber.Text .Chars(0))[/CODE]
1. The Chars() method extracts the first character (zero-based indexing).
2. Converts it to a 16-bit integer (0 to 65,534), because converting a single digit to anything bigger is a waste of memory.
3. The result is then stored into a 16-bit signed integer.
Note: You could also use Convert.ToByte (8-bit unsigned integer) and store in Byte data types to save even more memory because the numbers extracted can't be less than 0 and are obviously less than 255.
[CODE=vbnet]dim intSecond as Integer = Convert.toInt16 (txtNumber.Text .Chars(2))[/CODE]
1. The Chars() method extracts the third character (zero-based indexing).
2. Converts it to a 16-bit integer (0 to 65,534), because converting a single digit to anything bigger is a waste of memory.
3. The result is then stored into a 16-bit signed integer.
Note: You could also use Convert.ToByte (an 8-bit unsigned integer) and store in Byte data types to save even more memory because the numbers extracted can't be less than 0 and are obviously less than 255.
[CODE=vbnet]dim intAnswer as Integer = intFirst + intSecond[/CODE]
1. The first number and the second number variables are added together
2. The result is stored in a 16-bit signed integer
Note: As above, you can also use 8-bit unsigned integers.
[CODE=vbnet]MessageBox.Show (intAnswer.ToSt ring)[/CODE]
The answer is converted to a string for display into a dialog popup.Last edited by Killer42; Oct 29 '07, 01:57 AM. -
Thanks, that helps. When I put in the number "12345" into the textbox, it's giving me the answer 102. Any ideas on why it's giving me that answer?
Originally posted by cugoneEvery string object has a method ...Comment
-
Hi,
Use "SubString" :
[code=vb]
Dim intFirst As Short = Convert.ToInt16 (TextBox1.Text. Substring(0, 1))
Dim intSecond As Short = Convert.ToInt16 (TextBox1.Text. Substring(2, 1))
Dim intAnswer As Short = intFirst + intSecond
MessageBox.Show (intAnswer.ToSt ring)
[/code]
This adds First Digit and Third Digit..
Regards
VeenaComment
-
Comment