Getting 15th digit - vba

variable contains 15 digits,how to get 15th digit value from another function?
Function isvalid(stringvalue As String) As Boolean
Dim methodToCall As String
methodToCall = "somefunction"
isvalid = stringvalue Like "[0-9][0-9][A-Z][A-Z][A-Z][A-Z][A-Z]####[A-Z][A-Z][A-Z][methodToCall(stringvalue)]"
Here the methodToCall will call another function and that function is return value for my 15th digit
How to get the Value from anothor function from isvalid function

Say we have a string containing with a mixture of digits and other characters and we want the 15th digit. The UDF:
Public Function GetFifteenth(sin As String) As Variant
kount = 0
For i = 1 To Len(sin)
ch = Mid(sin, i, 1)
If IsNumeric(ch) Then
kount = kount + 1
If kount = 15 Then
GetFifteenth = CLng(ch)
Exit Function
End If
End If
Next i
GetFifteenth = ""
End Function
should do that. For example:
Sub MAIN()
Dim s As String, L As Variant
s = "t2}nf[aW(494U,Oay8OWkh{xa*9>9b2SY5yPt14;m98AYd$|>U%orIJ[iF*Q)0w21!0:eX9,kU<_ x=B+cAFU<)%#{JMSze}"
L = GetFifteenth(s)
MsgBox L
End Sub
The code would be a little simpler if the string always contained exactly 15 digits.

Related

Reversing Digits

I'm trying to make a function that takes a three digit number and reverses it (543 into 345)
I can't take that value from a TextBox because I need it to use the three numbers trick to find a value.
RVal = ReverseDigits(Val)
Diff = Val - RVal
RDiff = ReverseDigits(Diff)
OVal = Diff + RDiff
543-345=198
198+891=1089
Then it puts 1089 in a TextBox
Function ReverseDigits(ByVal Value As Integer) As Integer
' Take input as abc
' Output is (c * 100 + b * 10 + a) = cba
Dim ReturnValue As Boolean = True
Dim Val As String = CStr(InputTextBox.Text)
Dim a As Char = Val(0)
Dim b As Char = Val(1)
Dim c As Char = Val(2)
Value = (c * 100) + (b * 10) + (a)
Return ReturnValue
End Function
I've tried this but can't figure out why it won't work.
You can convert the integer to a string, reverse the string, then convert back to an integer. You may want to enforce the three digit requirement. You can validate the argument before attempting conversion
Public Function ReverseDigits(value As Integer) As Integer
If Not (value > 99 AndAlso value < 1000) Then Throw New ArgumentException("value")
Return Integer.Parse(New String(value.ToString().Reverse().ToArray()))
End Function
My code is pretty simple and will also work for numbers that don't have three digits assuming you remove that validation. To see what's wrong with your code, there are a couple of things. See the commented lines which I changed. The main issue is using Val as a variable name, then trying to index the string like Val(0). Val is a built in function to vb.net and the compiler may interpret Val(0) as a function instead of indexing a string.
Function ReverseDigits(ByVal Value As Integer) As Integer
' Dim ReturnValue As Boolean = True
' Dim Val As String = CStr(InputTextBox.Text)
Dim s As String = CStr(Value)
Dim a As Char = s(0)
Dim b As Char = s(1)
Dim c As Char = s(2)
Value = Val(c) * 100 + Val(b) * 10 + Val(a)
'Return ReturnValue
Return Value
End Function
(Or the reduced version of your function, but I would still not hard-code the indices because it's limiting your function from expanding to more or less than 3 digits)
Public Function ReverseDigits(Value As Integer) As Integer
Dim s = CStr(Value)
Return 100 * Val(s(2)) + 10 * Val(s(1)) + Val(s(0))
End Function
And you could call the function like this
Dim inputString = InputTextBox.Text
Dim inputNumber = Integer.Parse(inputString)
Dim reversedNumber = ReverseDigits(inputNumber)
Bonus: If you really want to use use math to find the reversed number, here is a version which works for any number of digits
Public Function ReverseDigits(value As Integer) As Integer
Dim s = CStr(value)
Dim result As Integer
For i = 0 To Len(s) - 1
result += CInt(Val(s(i)) * (10 ^ i))
Next
Return result
End Function
Here's a method I wrote recently when someone else posted basically the same question elsewhere, probably doing the same homework:
Private Function ReverseNumber(input As Integer) As Integer
Dim output = 0
Do Until input = 0
output = output * 10 + input Mod 10
input = input \ 10
Loop
Return output
End Function
That will work on a number of any length.

Take specific string part of string by specific requirments

I am developing function which would give me the right side of specific string. Function has possibility to take the return string based on splitted char, keep char in string and also which is most important to say either return string will be after last occurence of that char separator or say after exactly which positon of separator occerence in string, return string after to take. Can anyone take a look on that and confirm is it right way to go or whether that code contains any issues?
Keep in mind to use as lastindex i set lastindexof to true and doesn't matter what splitterCharPosition is and vice versa when false splitterCharPosition has to be set.
This is my current code to be confirmed:
Public Function GetRightSideStringByCHar(splitterChar As String, searchingWord As String, keepCharAsWell As Boolean, lastindexof As Boolean, splitterCharPosition As Integer) As String
Dim index As Integer
Select Case lastindexof
Case False
index = GetNthIndex(searchingWord, splitterChar, splitterCharPosition)
Case True
index = searchingWord.LastIndexOf(splitterChar)
End Select
If index > 0 Then
If keepCharAsWell Then
searchingWord = searchingWord.Substring(0, index + splitterChar.Length)
Else
searchingWord = searchingWord.Substring(0, index)
End If
Else
searchingWord = String.Empty
End If
Return searchingWord
End Function
Helper function to get n index:
Public Function GetNthIndex(searchingWord As String, charseparator As Char, n As Integer) As Integer
Dim count As Integer = 0
For i As Integer = 0 To searchingWord.Length - 1
If searchingWord(i) = charseparator Then
count += 1
If count = n Then
Return i
End If
End If
Next
Return -1
End Function
Based on your other deleted question, I formulated this for you.
It worked with all your previous examples.
[parameters]
str = input string
strtofind = separator string
occurance = zero-based index to start cutting (optional)
keepstringtofind = append separator to string (optional)
righttoleft = operational direction (optional)
Public Function CutFromString(str As String, strtofind As String, Optional occurance As Integer = 0, Optional keepstrtofind As Boolean = False, Optional righttoleft As Boolean = False) As String
Dim s As String = str
Dim sections As List(Of String) = IIf(String.IsNullOrEmpty(str), New List(Of String), str.Split(strtofind.ToCharArray).ToList)
If sections.Count = 1 AndAlso sections.First = str Then sections.Clear()
If occurance < sections.Count Then
Dim b = sections.Count - occurance
While b > 0
If righttoleft Then
sections.RemoveAt(0)
Else
sections.RemoveAt(sections.Count - 1)
End If
b -= 1
End While
s = Join(sections.ToArray, strtofind)
If keepstrtofind And occurance > 0 Then
If righttoleft Then
s = strtofind + s
Else
s += strtofind
End If
End If
End If
Return s
End Function

My vowel counter won't count in VB

I need to make a vowel then word counter in vb and it will not work. i have just tried the vowel bit for now but its not working. Any ideas ?
Dim analsyedtext As String
Dim lettercount As Integer
Dim i As Integer
lettercount = 0
Console.WriteLine("Please enter the text to be analysed.")
analsyedtext = Console.ReadLine()
If analsyedtext = "a" Or "e" Or "i" Or "o" Or "u" Then
lettercount = lettercount + 1
End If
Console.Writeline("The number of vowels is,{0}", lettercount)
End Sub
' My preferred function
Private Function VowelCount(str As String) As Integer
Dim vowels() As Char = "aeiou".ToCharArray()
Return (From letter In str.ToLower().ToCharArray()
Where vowels.Contains(letter)
Select letter).Count()
End Function
' This tests all of the functions and Asserts they're identical output
Sub Main()
For Each itm In {"this", "is", "some sort of", "a test that we're doing"}
Dim vowelNum = VowelCount(itm)
Console.WriteLine("{0}: {1}", itm, vowelNum)
Debug.Assert(vowelNum = VowelCount2(itm) AndAlso
vowelNum = VowelCount3(itm) AndAlso
vowelNum = VowelCount4(itm) AndAlso
vowelNum = VowelCount5(itm))
Next
Console.ReadLine()
End Sub
' Identical to above, different syntax
Private Function VowelCount2(str As String) As Integer
Dim vowels() As Char = "aeiou".ToCharArray()
Return str.ToLower().ToCharArray().Where(Function(ltr As Char) vowels.Contains(ltr)).Count()
End Function
' Uses another function IsVowel that does the same thing as vowels.Contains()
Private Function VowelCount3(str As String) As Integer
Dim vowelsInStr As New List(Of Char)
For Each letter As Char In str.ToLower().ToCharArray()
If IsVowel(letter) Then
vowelsInStr.Add(letter)
End If
Next
Return vowelsInStr.Count
End Function
' Different since this doesn't first put vowels into an IEnumerable and then count the vowels, it only does the count
Private Function VowelCount4(str As String) As Integer
Dim vowels() As Char = "aeiou".ToCharArray()
Dim count As Integer
For Each letter In str.ToLower().ToCharArray()
If IsVowel2(letter) Then
count += 1
End If
Next
Return count
End Function
' Same as above but uses a For loop instead of For Each
Private Function VowelCount5(str As String) As Integer
Dim vowels() As Char = "aeiou".ToCharArray()
Dim count As Integer
Dim letters() As Char = str.ToLower().ToCharArray()
For i = 0 To letters.Length - 1
If IsVowel2(letters(i)) Then
count += 1
End If
Next
Return count
End Function
Private Function IsVowel(ltr As Char) As Boolean
Dim vowels() As Char = "aeiou".ToCharArray()
Return vowels.Contains(ltr)
End Function
Private Function IsVowel2(ltr As Char) As Boolean
Dim vowels() As Char = "aeiou".ToCharArray()
For Each vowel As Char In vowels
If vowel = ltr Then
Return True
End If
Next
Return False
End Function
EDIT: Just realized there is more work for you to do, to get each individual letter. But assuming you get to the point where analsyedtext is one letter:
Select Case analsyedtext
Case "a", "e", "i", "o", "u"
lettercount += 1
Case Else
' Do nothing
End Select
What you need to do is examine the input string one character at a time.
You can extract one character at a time by using the SubString function like this (instead of your If..Then..End If piece of code):
For i = 0 To analsyedtext.Length - 1
Dim c = analsyedtext.Substring(i, 1)
If c = "a" OrElse c = "e" OrElse c = "i" OrElse c = "o" OrElse c = "u" Then
lettercount = lettercount + 1
End If
Next
Notice how it starts from zero and goes to analsyedtext.Length - 1 - that is because the first character has an index of zero.

Check String for identical Digits

I'm asking my users to enter a 4 - 6 digit numberic PIN. And I'd like to make sure users can't enter 0000 or 11111 or 333333. How can I check a string for 4 consecutive identical digits? I'm using vb.net.
See code snippet below:
Sub Main()
Dim a As String = "001111"
Dim b As String = "1123134"
Dim c As String = "1111"
Console.WriteLine(CheckConsecutiveChars(a, 4)) 'True => Invalid Pin
Console.WriteLine(CheckConsecutiveChars(b, 4)) 'False => Valid Pin
Console.WriteLine(CheckConsecutiveChars(c, 4)) 'True => Invalid Pin
Console.ReadLine()
End Sub
'maxnumber = maximum number of identical consecutive characters in a string
Public Function CheckConsecutiveChars(ByVal j As String, ByVal maxNumber As Integer) As Boolean
Dim index As Integer = 0
While ((index + maxNumber) <= j.Length)
If (j.Substring(index, maxNumber).Distinct.Count = 1) Then
Return True
End If
index = index + 1
End While
Return False
End Function
The method String.Distinct.Count() counts the number of distinct characters in a string. You cast your digit to a String and test for the number of different characters. If the result is 1 then the user has entered the same number.
Note: If you're using the Substring, you must check the length of the string first (is it long enough) to avoid exceptions.
This answer is similar to the accepted answer, but does not create lots of temporary strings in memory.
'maxnumber = maximum number of identical consecutive characters in a string
Public Function HasConsecutiveChars(ByVal j As String, ByVal maxNumber As Integer) As Boolean
Dim result As Boolean = False
Dim consecutiveChars As Integer = 1
Dim prevChar As Char = "x"c
For Each c in j
If c = prevChar Then
consecutiveChars += 1
If consecutiveChars >= maxNumber Then
result = True
Exit For
End If
Else
consecutiveChars = 1
End If
prevChar = c
Next
Return result
End Function

VBA. How to find position of first digit in string

I have string "ololo123".
I need get position of first digit - 1.
How to set mask of search ?
Here is a lightweight and fast method that avoids regex/reference additions, thus helping with overhead and transportability should that be an advantage.
Public Function GetNumLoc(xValue As String) As Integer
For GetNumLoc = 1 To Len(xValue)
If Mid(xValue, GetNumLoc, 1) Like "#" Then Exit Function
Next
GetNumLoc = 0
End Function
Something like this should do the trick for you:
Public Function GetPositionOfFirstNumericCharacter(ByVal s As String) As Integer
For i = 1 To Len(s)
Dim currentCharacter As String
currentCharacter = Mid(s, i, 1)
If IsNumeric(currentCharacter) = True Then
GetPositionOfFirstNumericCharacter = i
Exit Function
End If
Next i
End Function
You can then call it like this:
Dim iPosition as Integer
iPosition = GetPositionOfFirstNumericCharacter("ololo123")
Not sure on your environment, but this worked in Excel 2010
'Added reference for Microsoft VBScript Regular Expressions 5.5
Const myString As String = "ololo123"
Dim regex As New RegExp
Dim regmatch As MatchCollection
regex.Pattern = "\d"
Set regmatch = regex.Execute(myString)
MsgBox (regmatch.Item(0).FirstIndex) ' Outputs 5
I actually have that function:
Public Function GetNumericPosition(ByVal s As String) As Integer
Dim result As Integer
Dim i As Integer
Dim ii As Integer
result = -1
ii = Len(s)
For i = 1 To ii
If IsNumeric(Mid$(s, i, 1)) Then
result = i
Exit For
End If
Next
GetNumericPosition = result
End Function
You could try regex, and then you'd have two problems. My VBAfu is not up to snuff, but I'll give it a go:
Function FirstDigit(strData As String) As Integer
Dim RE As Object REMatches As Object
Set RE = CreateObject("vbscript.regexp")
With RE
.Pattern = "[0-9]"
End With
Set REMatches = RE.Execute(strData)
FirstDigit = REMatches(0).FirstIndex
End Function
Then you just call it with FirstDigit("ololo123").
If speed is an issue, this will run a bit faster than Robs (noi Rob):
Public Sub Example()
Const myString As String = "ololo123"
Dim position As Long
position = GetFirstNumeric(myString)
If position > 0 Then
MsgBox "Found numeric at postion " & position & "."
Else
MsgBox "Numeric not found."
End If
End Sub
Public Function GetFirstNumeric(ByVal value As String) As Long
Dim i As Long
Dim bytValue() As Byte
Dim lngRtnVal As Long
bytValue = value
For i = 0 To UBound(bytValue) Step 2
Select Case bytValue(i)
Case vbKey0 To vbKey9
If bytValue(i + 1) = 0 Then
lngRtnVal = (i \ 2) + 1
Exit For
End If
End Select
Next
GetFirstNumeric = lngRtnVal
End Function
An improved version of spere's answer (can't edit his answer), which works for any pattern
Private Function GetNumLoc(textValue As String, pattern As String) As Integer
For GetNumLoc = 1 To (Len(textValue) - Len(pattern) + 1)
If Mid(textValue, GetNumLoc, Len(pattern)) Like pattern Then Exit Function
Next
GetNumLoc = 0
End Function
To get the pattern value you can use this:
Private Function GetTextByPattern(textValue As String, pattern As String) As String
Dim NumLoc As Integer
For NumLoc = 1 To (Len(textValue) - Len(pattern) + 1)
If Mid(textValue, NumLoc, Len(pattern)) Like pattern Then
GetTextByPattern = Mid(textValue, NumLoc, Len(pattern))
Exit Function
End If
Next
GetTextByPattern = ""
End Function
Example use:
dim bill as String
bill = "BILLNUMBER 2202/1132/1 PT2200136"
Debug.Print GetNumLoc(bill , "PT#######")
'Printed result:
'24
Debug.Print GetTextByPattern(bill , "PT#######")
'Printed result:
'PT2200136