My vowel counter won't count in VB - vb.net

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.

Related

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

Select the first 2 Characters of each word on String

I created the following function, but have not been able to finish. I want to return the first 2 characters of each word in the string. Here is what I have so far:
Function SelectWords(ByVal text As String, ByVal maxWords As Integer) As String
If String.IsNullOrEmpty(text) Then Return String.Empty
If maxWords <= 0 Then Return String.Empty
Dim words As String() = text.Split(" "c)
Return String ''I am stuck here
End Function
You did not describe the purpose of maxwords, nor what to do with a. The loop part:
Dim words = str.Split(" "c)
Dim ret As New StringBuilder ' in case it is a long string
For Each w As String In words
If w.Length > 1 Then
ret.Append(w.Substring(0, 2))
Else
' decide if you want 1
End If
Next
return ret.toString
The code you have doesn't do anything that you describing .. Try this function instead.
Function SelectWords(ByVal text As String, ByVal maxWords As Integer) As String
Dim collection As MatchCollection = Regex.Matches(text, "(\w{2})\w*\b")
Dim output As New System.Text.StringBuilder
Dim counter As Integer = 0
For Each M As Match In collection
output.Append(M.Groups(1).Value)
counter += 1
If counter = maxWords Then
Exit For
End If
Next
Return output.ToString
End Function

Count number of characters after specific character in textbox

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

get combinations with repetition

How can I write all possible combinations to the console? For example, if user enters abc, then it will write aaa, aab, aac, abb, abc, acc, bbb, bbc, ccc. Please help me.
Here's some code:
Dim abc() As String = {"a", "b", "c"} '
Sub Main()
Console.WriteLine("Enter the amount of characters")
Dim count As Integer = Console.ReadLine
outputStrings("", count)
Console.ReadLine()
End Sub
Private Sub outputStrings(ByVal startString As String, ByVal letterCount As Integer)
For i = 0 To abc.Length - 1
Dim temp As String = startString
temp += abc(i)
If temp.Length = letterCount Then
Console.WriteLine(temp)
If i = abc.Length - 1 Then
Console.WriteLine("----")
End If
Else
outputStrings(temp, letterCount)
End If
Next
End Sub
Something has to be done after the dashed lines to remove unwanted permutation to leave out only valid combinations.
You can restrict the letters used to ones at or to the right of abc(i) with an additional parameter abcIndex, and start the for loop from there. Only strings which have their letters in alphabetical order will be written, which prevents duplicates.
Private Sub outputStrings(ByVal startString As String, ByVal letterCount As Integer, ByVal abcIndex As Integer)
For i = abcIndex To abc.Length - 1
Dim temp As String = startString
temp += abc(i)
If temp.Length = letterCount Then
Console.WriteLine(temp)
Else
outputStrings(temp, letterCount, i)
End If
Next
End Sub
Call with:
outputStrings("", 3, 0)
def go(chars,thusfar):
if len(thusfar) = len(chars):
print thusfar
for char in chars:
go(chars,thusfar+char);
This should be easy enough to translate to VB (read: I don't know VB)
You just need to make a recursive call there.
Dim abc() As String = {"a", "b", "c"} '
Sub Main()
Console.WriteLine("Enter the amount of characters")
Dim count As Integer = Console.ReadLine
outputStrings("", count)
Console.ReadLine()
End Sub
Private Sub outputStrings(ByVal startString As String, ByVal letterCount As Integer)
For i = 0 To abc.Count - 1
Dim temp As String = startString
temp += abc(i)
If temp.Length = letterCount Then
Console.WriteLine(temp)
Else
outputStrings(temp, letterCount)
End If
Next
End Sub
Do note that if someone enters a negative number that your code will run forever. I'll leave fixing that as an easy exercise.
Amazing code from here:
Private Shared Function PermutationsWithRepetition(Of T)(list As IEnumerable(Of T), length As Integer) As IEnumerable(Of IEnumerable(Of T))
If length = 1 Then
Return list.[Select](Function(x) New T() {x})
End If
Return PermutationsWithRepetition(list, length - 1).SelectMany(Function(x) list, Function(t1, t2) t1.Concat(New T() {t2}))
End Function
Can be used with Integer, Char, Double etc.
Example of use:
Dim myarray(1) As Integer
myarray(0) = 1
myarray(1) = 2
Dim k As Integer = 2 'number of "slots" to do the permutations
mypermutations = PermutationsWithRepetition(myarray,k)
For Each row As IEnumerable(Of Integer) In mypermutations
Console.WriteLine("")
For Each col As IntegerIn row
Console.Write(col.toString())
Next
Next
Output:
11
12
21
22

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