Best way to get the first digit from an integer of varying length in VB.NET - vb.net

I am a newbie to programming and need some help with the basics.
I have a function which takes in an integer value. I want to be able to grab the first digit (or the first and second digits in some cases) of this integer and do something with it.
What is the best way in VB.NET to get the first digit of an integer (or the first and second)?

firstDigit = number.ToString().Substring(0,1)
firstTwoDigits = number.ToString().Substring(0,2);
int.Parse(firstDigit)
int.Parse(firstTwoDigits)
and so forth

I'm not well versed in VB syntax, so forgive me for the syntax errors:
dim i as integer
while i >= 10
i = i \ 10
end while
msgbox "i = " & i
Note, this prints the "first from the left" digit. Like, for "12345" it would print "1".

If you need the digits starting from the end of the integer, just get the modulu result for the tens or the hundreds, according to how many digits you need.
Dim n As Integer
n Mod 10
for the first digit, or:
n Mod 100
for the second and first digits.
If you need the first and second digits from the beginning of the number, there is another answer here which will probably help you.

for first digit you can use:
Dim number As Integer = 234734
Dim first = number.ToString.ToCharArray()(0)
for second digit you can use:
Dim number As Integer = 234734
Dim second = number.ToString.ToCharArray()(1)

This would work. You can use Math.ABS, absolute value, to eliminate negative. The number from left could be replaced by a function if you are using logic, like the overall length of the number, to determine how many of the leading characters you are going to use.
Dim number As Integer = -107
Dim result As String
Dim numberFromLeft As Integer = 2
result = Math.Abs(number).ToString.Substring(0, numberFromLeft)
This results in 10 it is a string but converting it back to a number is easy if you need to. If you need to keep track if it was positive or negative you could use the original value to apply that back to you parsed string.

Related

Incrementing 5 digit number, including leading zeros

I need to generate statement numbers in Access 2016. These numbers need to be 5 digits long, and where the statement number is less than 5 digits, I need to pad the number with leading zeros.
As a starting point, the first statement number will not be padded. So if the last statement number is 96, the next statement number needs to be 00097.
Is it possible (I assume in VBA) to cater for both cases, where the number is 5 digits long, or where it is less.
I was thinking of firstly stripping the leading zeros from the last statement number (if any existed), incrementing the remaining number by one, and then adding leading zeros to make the length of the number 5, but I'm not sure of the most efficient way of doing this.
If it has a leading zero, it will not be a number, but a String. However, as far as it is not quite a bit difference, something like this works:
Sub TestMe()
Dim cnt As Long
Dim myString As String
For cnt = 98 To 120
myString = Format(cnt, "00000")
Debug.Print myString
Next cnt
End Sub
This is what you get in the immediate window:
00098
00099
00100
00101
Yes, just first convert to a number:
NextValue = Format(Val(CurrentValue) + 1, "00000")
You could also use:
NextStateStr = Right("00000" & LastStateNum + 1, 5)

Get the nth character, string, or number after delimiter in Visual Basic

In VB.net (Visual Studio 2015) how can I get the nth string (or number) in a comma-separated list?Say I have a comma-separated list of numbers like so:13,1,6,7,2,12,9,3,5,11,4,8,10How can I get, say, the 5th value in this string, in this case 12?I've looked at the Split function, but it converts a string into an array. I guess I could do that and then get the 5th element of that array, but that seems like a lot to go through just to get the 5th element. Is there a more direct way to do this, or am I pretty much limited to the Split function?
In case you are looking for an alternative method, which is more basic, you can try this:
Module Module1
Sub Main()
Dim a As String = "13,1,6,7,2,12,9,3,5,11,4,8,10"
Dim counter As Integer = 5 'the number you want (in this case, 5th one)
Dim movingcounter As Integer = 0 'how many times we have moved
Dim startofnumber, endofnumber, i As Integer
Dim numberthatIwant As String
Do Until movingcounter = counter
startofnumber = InStr(i + 1, a, ",")
i = startofnumber
movingcounter = movingcounter + 1
Loop
endofnumber = InStr(startofnumber + 1, a, ",")
numberthatIwant = (Mid(a, startofnumber + 1, endofnumber - startofnumber - 1))
Console.WriteLine("The number that I want: " + numberthatIwant)
Console.ReadLine()
End Sub
End Module
Edit: You can make this into a procedure or function if you wish to use it in a larger program, but this code run in console mode will give the output of 12.
The solution provided by Plutonix as a comment to my question is straightforward and exactly what I was looking for, to wit:result = csv.Split(","c)(5)In my case I was incrementing a variable each time my program ran and needed to get the nth character or string after the incremented value. That is, if my program had incremented the variable 5 times, then I needed the string after the 4th comma, which of course, is the 5th string. So my solution was something like this:result = WholeString.Split(","c)(IncrementedVariable)Note that this is a zero-based variable.Thanks, Plutonix.

Find Nth number in a long variable in vbnet

I have a very long number that goes like this:
numb as long=011212201220200112202001200101121220200120010112200101120112122....
It will be more than 4,000,000,000 digits. My problem is to find any digit in the number. If it was integer I would convert to string and do this:
numb(200)
But his is Long. Do you know how to find this?
As with integers, you can convert a long into a string too, in order to get the n-th element
Dim numb As Long = 9876543210
Dim targetDigit As Integer = 3 ' Set target as the 3rd digit
numb.ToString()(targetDigit -1) ' Retuns the 3rd digit: 7
Side note: I suspect that you may know this but, a long datatype can only hold
Integers ranging in value from -9,223,372,036,854,775,808 through 9,223,372,036,854,775,807
That's only 19 digits! No where near 4 billion.
Source: MSDN

Extract 5-digit number from one column to another

I need help with extracting 5-digit numbers only from one column to another in Excel 2010. These numbers can be in any position of the string (beginning of the string, anywhere in the middle, or at the end). They can be within brackets or quotes like:
(15478) or "15478" or '15478' or [15478]
I need to ignore any numbers that are less than 5 digits and include numbers that start with 1 or more leading zeros (like 00052, 00278, etc.) and ensure that leading zeros are copied over to the next column. Could someone help me with either creating a formula or UDF?
Here is a formula-based alternative that will extract the first 5 digit number found in cell A1. I tend to prefer reasonably simple formula solutions over VBA in most situations as formulas are more portable. This formula is an array formula and thus must be entered with Ctrl+Shift+Enter. The idea is to split the string up into every possible 5 character chunk and test each one and return the first match.
=MID(A1,MIN(IF(NOT(ISERROR(("1"&MID(A1,ROW(INDIRECT("R1C[1]:R"&(LEN(A1)-4)&"C[1]",FALSE)),5)&".1")*1))*ISERROR(MID(A1,ROW(INDIRECT("R1C[1]:R"&(LEN(A1)-4)&"C[1]",FALSE))+5,1)*1)*ISERROR(MID(A1,ROW(INDIRECT("R1C[1]:R"&(LEN(A1)-4)&"C[1]",FALSE))-1,1)*1),ROW(INDIRECT("R1C[1]:R"&(LEN(A1)-4)&"C[1]",FALSE)),9999999999)),5)
Let's break this down. First we have an expression I used twice to return an array of numbers from 1 up to 4 less than the length of your initial text. So if you have a string of length 10 the following will return {1,2,3,4,5,6}. Hereafter the below formula will be referred to as rowlist. I used R1C1 notation to avoid potential circular references.
ROW(INDIRECT("R1C[1]:R"&(LEN(A1)-4)&"C[1]",FALSE))
Next we will use that array to split the text into an array of 5 letter chunks and test each chunk. The test being performed is to prepend a "1" and append ".1" then verify the chunk is numeric. The prepend and append eliminate the possibility of white space or decimals. We can then check the character before and the character after to make sure they are not numbers. Hereafter the below formula will be referred to as isnumarray.
NOT(ISERROR(("1"&MID(A1,rowlist,5)&".1")*1))
*ISERROR(MID(A1,rowlist+5,1)*1)
*ISERROR(MID(A1,rowlist-1,1)*1)
Next we need to find the first valid 5 digit number in the string by returning the current index from a duplicate of the rowlist formula and returning a large number for non-matches. Then we can use the MIN function to grab that first match. Hereafter the below will be referred to as minindex.
MIN(IF(isnumarray,rowlist,9999999999))
Finally we need to grab the numeric string that started at the index returned by the MIN function.
MID(A1,minindex,5)
The following UDF will return the first five digit number in the string, including any leading zero's. If you need to detect if there is more than one five digit number, the modifications are trivial. It will return a #VALUE! error if there are no five-digit numbers.
Option Explicit
Function FiveDigit(S As String, Optional index As Long = 0) As String
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
With RE
.Pattern = "(?:\b|\D)(\d{5})(?:\b|\D)"
.Global = True
FiveDigit = .Execute(S)(index).submatches(0)
End With
End Function
As you may see from the discussion between Mark and myself, some of your specifications are unclear. But if you would want to exclude decimal numbers, when the decimal portion has five digits, then the regex pattern in my code above should be changed:
.Pattern = "(?:\d+\.\d+)|(?:\b|\D)(\d{5})(?:\b|\D)"
I just wrote this UDF for you , basic but will do it...
It will find the first 5 consecutive numbers in a string, very crude error checking so it just says Error if anything isn't right
Public Function GET5DIGITS(value As String) As String
Dim sResult As String
Dim iLen As Integer
sResult = ""
iLen = 0
For i = 1 To Len(value)
If IsNumeric(Mid(value, i, 1)) Then
sResult = sResult & Mid(value, i, 1)
iLen = iLen + 1
Else
sResult = ""
iLen = 0
End If
If iLen = 5 Then Exit For
Next
If iLen = 5 Then
GET5DIGITS = Format(sResult, "00000")
Else
GET5DIGITS = "Error"
End If
End Function

Shortening a repeating sequence in a string

I have built a blog platform in VB.NET where the audience are very young, and for some reason like to express their commitment by repeating sequences of characters in their comments.
Examples:
Hi!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3
LOLOLOLOLOLOLOLOLOLOLOLOLLOLOLOLOLOLOLOLOLOLOLOLOL
..and so on.
I don't want to filter this out completely, however, I would like to shorten it down to a maximum of 5 repeating characters or sequences in a row.
I have no problem writing a function to handle a single repeating character. But what is the most effective way to filter out a repeating sequence as well?
This is what I used earlier for the single repeating characters
Private Shared Function RemoveSequence(ByVal str As String) As String
Dim sb As New System.Text.StringBuilder
sb.Capacity = str.Length
Dim c As Char
Dim prev As Char = String.Empty
Dim prevCount As Integer = 0
For i As Integer = 0 To str.Length - 1
c = str(i)
If c = prev Then
If prevCount < 10 Then
sb.Append(c)
End If
prevCount += 1
Else
sb.Append(c)
prevCount = 0
End If
prev = c
Next
Return sb.ToString
End Function
Any help would be greatly appreciated
You should be able to recursively use the 'Longest repeated substring problem' to solve this. On the first pass you will get two matching sub-strings, and will need to check if they are contiguous. Then repeat the step for one of the sub-strings. Cut off the algo, if the strings are not contiguous, or if the string size become less than a certain number of characters. Finally, you should be able to keep the last match, and discard the rest. You will need to dig around for an implementation :(
Also have a look at this previously asked question: finding long repeated substrings in a massive string