Count number of characters after specific character in textbox - vb.net

using winforms / vb.net
I am trying to count how many characters exist in "textbox3" after a specific character "." in a textbox.
examples:
2adf = 0 (no "." exists)
2adf. = 0
2adf.2 = 1
2adf.2a = 2
2adf.2af = 3
2adf.2afe = 4
I already have a function to search if there is a "."
if (CountCharacter(TextBox3.Text, ".") = 1) then
'a "." exists so count number of characters after "."
end if
Public Function CountCharacter(ByVal value As String, ByVal ch As Char) As Integer
Dim cnt As Integer = 0
For Each c As Char In value
If c = ch Then cnt += 1
Next
Return cnt
End Function
I am not sure how to check the count after the "." though

You could use the string.IndexOf method for this task
Sub Main
Dim test = "2adf.2afe"
Dim result = CountCharsAfter(test, "."c)
Console.WriteLine(result)
End Sub
Public Function CountCharsAfter(input as string, charToSearch as Char) as Integer
DIm pos = input.LastIndexOf(charToSearch)
if pos = -1 then
return 0
else
return input.Length - (pos + 1)
End if
End Function

Try this
Dim NoChar As Integer = CalculateChra("12adf.2afe", ".")
Private Function CalculateChra(ByVal V_String As String, ByVal LastChar As Char) As Integer
Dim Start As String = Split(V_String, LastChar)(0) & "."
Dim M As String = V_String.Substring(Start.Length)
Return M.Length
End Function

dim n,cnt as integer
n=0
cnt=0
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If e.KeyChar = Chr(46) Then
n = Len(TextBox1.Text)
End If
If n <> 0 Then
cnt += 1
End If
MsgBox(" no.of charectors after '.' is/are : " & cnt - 1)
End Sub

Related

Convert hex little endian to decimal number

I understand how to convert decimal to hexadecimal (little endian).
Dec : 579270022
Hex : 86F58622 (little endian)
My sample code:
Public Shared Function decimalToHexLittleEndian(ByVal _iValue As Long, ByVal _iBytes As Integer) As String
Dim sBigEndian As String = String.Format("{0:x" & (2 * _iBytes).ToString() & "}", _iValue)
Dim sLittleEndian = ""
For i = _iBytes - 1 To 0 Step -1
sLittleEndian += sBigEndian.Substring(i * 2, 2)
Next
Return sLittleEndian
End Function
Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
TextBox2.Text = decimalToHexLittleEndian("579270022", 4)
End Sub
Now, my question is how convert hexadecimal (little endian) to decimal?
Reverse the pairs of characters and then use Convert.ToInt64(r, 16):
Dim h = "86F58622"
' Ensure an even length
If h.Length Mod 2 = 1 Then h = "0" & h
Dim r = ""
For i = 0 To h.Length - 1 Step 2
r = h.Substring(i, 2) & r
Next
Dim a = Convert.ToInt64(r, 16)
Console.WriteLine(a) ' outputs 579270022

How do I assign a default property to a FunctionProcedureName() in VB.NET?

I have done extensive research on using recursion in VB.NET (I am using 2015) in order complete a homework assignment. In my desperation, I even asked my professor for help!
I am trying to write a program that will calculate 1! through 12!, and post the results in a list box. The method I am using is based on the following example (sent to me by my prof):
var integer n, result
n = 0
For 1 to 12 do
n = n + 1
write (n, ‘! equals ‘, Fact(n)
End For
Function Fact (ByVal n as Integer)
if (n = 0) then Fact = 1
else Fact = n * Fact (n-1)
End If
End Function
http://www.softwareandfinance.com/VB/Factorial_Recursion.html
My issue is with my call statement for the function (I named it Factorial). Here is the section of the code where I am getting the error message:
For intN = 1 To 12
intFact = Factorial()
lstFactorialsAnswers.Items.Add(intN & "! = " & intFact)
Next
Thank you for your insights.
In response, I removed the "Dim Factorial as Int64" declaration. I also added "intN" as a parameter in the function call. The new error message is "Argument not specified for parameter 'intFact' of 'Public Function Factorial(intN As Integer, intFact As Integer) As Long'.
Here is the revised code:
Public Class frmFactorialMath
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
Dim intN As Integer
Dim intFact As Integer
intN = Convert.ToInt32(txtN)
For intN = 1 To 12
If intN = 1 Then
lstFactorialsAnswers.Items.Add(intN & "! = " & 1)
Else
intFact = Factorial(intN)
lstFactorialsAnswers.Items.Add(intN & "! = " & intFact)
End If
Next
End Sub
Function Factorial(ByVal intN As Integer, intFact As Integer) As Long
If (intN = 0) Then
Return 1
Else
intFact = intN * Factorial(intN - 1)
Return intFact
End If
End Function
Here is the solution to the issue(s) I was having:
Option Strict On
Public Class frmFactorialMath
' This event handler calculates the factorials for numbers 1 through 12.
' A list showing the answers is compiled and displayed.
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
Dim intN, intFact As Integer
For intN = 1 To 12
intFact = Factorial(intN)
lstFactorialsAnswers.Items.Add(intN.ToString() & "! = " & intFact.ToString())
Next
End Sub
' This Function performs the calculations using recursion.
Function Factorial(ByVal intFact As Integer) As Integer
If intFact = 1 Then
Return 1
Else
' This "Do While" loop ends the recursion, eliminating an infinite loop.
Do While intFact > 1
Return intFact * Factorial(intFact - 1)
Loop
End If
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.

vb .net permutation of string. permutation or combination?

i've got arary of string like this C - F - A - M. i want to create a combination from that with condition:
each other item beside last character has to be combined with last character
there's not allowed a same combination, even the order is different. for example
FC - M
CF - M
if the string array contains >=3 element it will generate 2 & 3 itemset, if 2 element then it will generate only 2 itemset
below is my code. my code generate the result like right part of the picture
my question is what method should i use? is it permutation, combination, or other things?
and in pseudocode, what is my case would be like?
here's my code
Public Class permute
Dim ItemUsed() As Boolean
Dim pno As Long, pString As String
Dim inChars() As Char = {"c", "f", "a", "m"}
Private Sub permute_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Sub Permute(ByVal K As Long)
ReDim ItemUsed(K)
pno = 0
Dim i As Integer
For i = 2 To K
Permutate(i, 1)
tb.Text = K
Next
End Sub
Private Sub Permutate(ByVal K As Long, ByVal pLevel As Long)
Dim i As Long, Perm As String
Perm = pString
For i = 0 To K - 1
If Not ItemUsed(i) Then
If pLevel = 1 Then
pString = inChars(i)
Else
pString += inChars(i)
End If
If pLevel = K Then
pno = pno + 1
Results.Text += _
pno & " " & " = " & " " & pString & vbCrLf
Exit Sub
End If
ItemUsed(i) = True
Permutate(K, pLevel + 1)
ItemUsed(i) = False
pString = Perm
End If
Next
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Permute(tb.Text)
End Sub
Private Sub tb_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tb.TextChanged
If tb.Text = "" Then
Results.Text = ""
Else
Permute(tb.Text)
End If
End Sub
End Class
here's the requirement screenshot
and here's the program screenshot
Add this class to your project:
Public NotInheritable Class Permutation
Public Shared Function Create(array As Char()) As List(Of String)
Return Permutation.Create(array, False)
End Function
Public Shared Function Create(array As Char(), sort As Boolean) As List(Of String)
If (array Is Nothing) Then
Throw New ArgumentNullException("array")
ElseIf ((array.Length < 0) OrElse (array.Length > 13)) Then
Throw New ArgumentOutOfRangeException("array")
End If
Dim list As New List(Of String)
Dim n As Integer = array.Length
Permutation.Permute(list, array, 0, array.Length)
If (sort) Then
list.Sort()
End If
Return list
End Function
Private Shared Sub Permute(list As List(Of String), array As Char(), start As Integer, n As Integer)
Permutation.Print(list, array, n)
If (start < n) Then
Dim i, j As Integer
For i = (n - 2) To start Step -1
For j = (i + 1) To (n - 1)
Permutation.Swap(array, i, j)
Permutation.Permute(list, array, (i + 1), n)
Next
Permutation.RotateLeft(array, i, n)
Next
End If
End Sub
Private Shared Sub Print(list As List(Of String), array As Char(), size As Integer)
If (array.Length <> 0) Then
Dim s As Char() = New Char(size - 1) {}
For i As Integer = 0 To (size - 1)
s(i) = array(i)
Next
list.Add(s)
End If
End Sub
Private Shared Sub RotateLeft(array As Char(), start As Integer, n As Integer)
Dim tmp As Char = array(start)
For i As Integer = start To (n - 2)
array(i) = array(i + 1)
Next
array(n - 1) = tmp
End Sub
Private Shared Sub Swap(array As Char(), i As Integer, j As Integer)
Dim tmp As Char
tmp = array(i)
array(i) = array(j)
array(j) = tmp
End Sub
End Class
Because of the Int32.MaxValue limit this class will support levels 1 through 13.
s=1, n=1
s=2, n=2
s=3, n=6
s=4, n=24
s=5, n=120
s=6, n=720
s=7, n=5040
s=8, n=40320
s=9, n=362880
s=10, n=3628800
s=11, n=39916800
s=12, n=479001600
s=13, n=6227020800
Usage:
Me.TextBox1.Text = String.Join(Environment.NewLine, Permutation.Create({"c"c, "f"c, "a"c, "m"c}, sort:=False))
Output:
cfam
cfma
cafm
camf
cmfa
cmaf
fcam
fcma
facm
famc
fmca
fmac
acfm
acmf
afcm
afmc
amcf
amfc
mcfa
mcaf
mfca
mfac
macf
mafc
The class is based on C++ code from the following link:
Calculating Permutations and Job Interview Questions
This seems to be a Combination problem rather than Permutation :
"In mathematics, a combination is a way of selecting several things out of a larger group, where (unlike permutations) order does not matter". [Wikipedia]
Try to solve this by doing Combination to all item in array except the last item. Or in other words, do Combination operations nCk for all k, with
n = size of input array minus the last item
k = size of the output itemset, minimum k is 1 and maximum is n
Then append each Combination result with the last item. Following is the pseudocode code, using C# syntax :p
var input = new char[] {'C', 'F', 'A', 'M'};
//save last char
var lastChar = input[input.Length - 1];
//combinationInput is input member without the last character
var combinationInput = new char[input.Length - 1];
Array.Copy(input, 0, combinationInput, 0, combinationInput.Length);
//generate output with itemset size 1 to combinationInput.Length
for (int i = 1; i <= combinationInput.Length; i++)
{
//generate combination with size i
var combinationOutput = combinationInput.Combinations(i);
foreach (var combinedChar in combinationOutput)
{
//print output as: combinationOutput item + lastChar
Console.WriteLine(string.Join(", ", combinedChar) + ", " + lastChar);
}
}
References :
Array.Copy(...). [How to copy part of an array to another array]
.Combinations(int outputSize) extension method. [How to Generate Combinations of Elements of a List in .NET 4.0]

Code is clean but when running it will not display

Public Class Form1
Private Sub GenerateAndSearch(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGenerate.Click, btnSearch.Click
Static intDataArray(-1) As Integer
Dim btnButtonClicked As Button = sender
Select Case btnButtonClicked.Tag
Case "Generate Array"
Call GenerateSortedArray(intDataArray)
Me.lstListArrayElements.Items.Clear()
Call DisplayData(intDataArray, Me.lstListArrayElements, "Sorted array:")
Case "Search Array"
Dim intNumToFind As Integer = Val(Me.txtNumToFind.Text)
Dim intNumFoundIndex As Integer
intNumFoundIndex = BinarySearch(intDataArray, intNumToFind)
If intNumFoundIndex = -1 Then
Me.lblFoundMessage.Text = "Number not found."
Else
Me.lblFoundMessage.Text = "Number found at index" & intNumFoundIndex
End If
End Select
End Sub
Sub GenerateSortedArray(ByRef intArray() As Integer)
Const intNUMELEMENTS As Integer = 50
Const intMAXNUMBER As Integer = 100
ReDim intArray(intNumElements - 1)
Randomize()
Dim intIndex As Integer
For intIndex = 0 To intArray.Length - 1
intArray(intIndex) = Int(intMAXNUMBER * Rnd()) + 1
Next intIndex
Call InsertionSort(intArray)
End Sub
Sub InsertionSort(ByRef intArray() As Integer)
Dim intIndex, intPreviousIndex, intTempItem As Integer
For intIndex = 1 To intArray.Length - 1
intTempItem = intArray(intIndex)
intPreviousIndex = intIndex - 1
Do While intPreviousIndex > 0 And
intArray(intPreviousIndex) > intTempItem
intArray(intPreviousIndex + 1) = intArray(intPreviousIndex)
intPreviousIndex = intPreviousIndex - 1
Loop
If intArray(intPreviousIndex) > intTempItem Then
intArray(intPreviousIndex + 1) = intArray(intPreviousIndex)
intArray(intPreviousIndex) = intTempItem
Else
intArray(intPreviousIndex + 1) = intTempItem
End If
Next intIndex
End Sub
Sub DisplayData(ByRef intArray() As Integer, ByRef lstList As ListBox, ByVal strTitle As String)
lstList.Items.Add(strTitle)
Dim intIndex As Integer
For intIndex = 0 To intArray.Length - 1
lstList.Items.Add(intIndex & vbTab & intArray(intIndex))
Next intIndex
End Sub
Function BinarySearch(ByRef intArray() As Integer, ByVal intNumToFind As Integer) As Integer
Dim intHighIndex As Integer = intArray.Length - 1
Dim intMidIndex As Integer
Dim intLowIndex As Integer = 0
Dim blnFound As Boolean = False
Do While (Not blnFound) And (intLowIndex <= intHighIndex)
intMidIndex = (intMidIndex + intLowIndex) / 2
If intArray(intMidIndex) = intNumToFind Then
blnFound = True
ElseIf intArray(intMidIndex) > intNumToFind Then
intHighIndex = intMidIndex - 1
Else
intLowIndex = intMidIndex + 1
End If
Loop
If blnFound Then
Return intMidIndex
Else
Return -1
End If
End Function
Private Sub NewData_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtNumtoFind.TextChanged, btnGenerate.Click
Me.lblFoundMessage.text = Nothing
End Sub
End Class
My problem is I cannot get my code to display a list of arrays to find. I cant see where im going wrong any ideas? Also my sort button is not working but that may be due to the fact nothing shows up when i click button btnGenerate.
Your biggest problem appears to be in your BinarySearch function. The reason you weren't getting any display is the BinarySearch function had an infinite loop. Here's some corrected code with explanations and is tested and working:
Function BinarySearch(ByRef intArray() As Integer, ByVal intNumToFind As Integer) As Integer
Dim intHighIndex As Integer = intArray.Length - 1
Dim intMidIndex As Integer
Dim intLowIndex As Integer = 0
Dim blnFound As Boolean = False
Do While (Not blnFound) And (intLowIndex <= intHighIndex)
'This should add high and low then divide by 2 not mid and low
'Also you should use the integer division sign to return an integer result
intMidIndex = (intHighIndex + intLowIndex) \ 2
If intArray(intMidIndex) = intNumToFind Then
blnFound = True
'mid should become the new limit without any inc/decrement
ElseIf intArray(intMidIndex) > intNumToFind Then
intHighIndex = intMidIndex
Else
intLowIndex = intMidIndex
End If
Loop
If blnFound Then
Return intMidIndex
Else
Return -1
End If
End Function
A couple of other corrections that should be made:
Select Case btnButtonClicked.Tag should be Select Case btnButtonClicked.Tag.ToString()
intArray(intIndex) = Int(intMAXNUMBER * Rnd()) + 1 should be intArray(intIndex) = CInt(intMAXNUMBER * Rnd()) + 1
One other thought, you might want to put a check in the generate routine to only generate unique numbers. Binary search will only find one element but not any of the others if there are more.
The NewData_TextChanged method erases your search results:
Me.lblFoundMessage.text = Nothing
Remove that line of code and the results should be displayed.