I'm teaching myself VB.net and I'm trying to complete challenges.
I'm stuck on this challenge.
I'm trying to figure out how to go about counting specific characters in a string using SubString.
I should not use string processing functions other than: Trim, ToUpper, ToLower, Indexof, SubString.
Add one button for each vowel of the alphabet. When clicked, the output is the count of that vowel in the text entered.Using SubString, the code under the button click event handler,displays how many times the corresponding character appears in the text.
This is what I have so far, but how should I incorporate SubString?
Dim counter As Integer = 0
For Each vowelA As Char In TextBox1.Text
If vowelA = "a" Then
counter += 1
End If
If vowelA = "A" Then
counter += 1
End If
Next
Here I incorporated also .ToUpper so you don't need to compare "a" and "A"
Dim counter As Integer = 0
For i = 0 To TextBox1.Text.Length - 1
If TextBox1.Text.ToUpper.Substring(i, 1) = "A" Then
counter += 1
End If
Next
Without using a substring() function,
Function count_vowels(ByVal str As String, ByVal chr As String) As Integer
str = str.ToUpper()
chr = chr.ToUpper()
count_vowels = str.Split(chr).Length - 1
Return count_vowels
End Function
Usage:
Dim counter As Integer = 0
counter = count_vowels(TextBox3.Text, "a")
or simply use
counter = TextBox1.Text.ToUpper.Split("a".ToUpper).Length - 1
Try something like this:
Dim pos As Integer = 0
Dim letter as String
While pos < TextBox1.Text.Length
letter = TextBox1.Text.Substring(pos, 1)
If letter = "A" Then
counter += 1
End If
pos += 1
End While
Related
I making matrix calculator. so, Textbox_A contains vbCrLf and tries to put it in Array_A.
and I would like to put Array_A in Result Matrix.
It's like
Textbox_a:
(1 2 3)
(4 5 6)
[Matrix to Array]
Array_a(0)(0) = 1
Array_a(0)(1) = 2
Array_a(0)(2) = 3
Array_a(1)(0) = 4
...
I have done string splits through several articles, but changing them to integers causes many problems.
This picture is Matrix_A and result Matrix
I don't know if the size of your initial matrix, formatted as text, is fixed, but here is some code to help you get started. The code tries to calculate the number of columns and rows.
The actual code is in the TextToArray function, that takes as input as string formatted as you described:
(1 2 3) (cr/lf)
(4 5 6)
and outputs a two dimensional array. The Main sub is just used to call TextToArray and display results.
So, in your example, you should pass TextBox_A.Text to TextToArray
There is minimal error checking here - you should add more to validate that data entered are numbers (check the Integer.TryParse function) and that the number of columns is the same across lines.
Sub Main(args As String())
Dim myInput As String = "(1 2 3)" & vbCrLf & "(4 5 6)"
Dim ret As Integer(,) = TextToArray(myInput)
If ret IsNot Nothing Then
For i As Integer = 0 To ret.GetUpperBound(0) - 1
For n As Integer = 0 To ret.GetUpperBound(1) - 1
Console.WriteLine(i & "," & n & "=" & ret(i, n))
Next
Next
Else
Console.WriteLine("No results - wrong input format")
End If
Console.ReadLine()
End Sub
Private Function TextToArray(matrix As String) As Integer(,)
Dim noOfRows As Integer = matrix.Split(vbCrLf).Count
Dim noOfColumns As Integer = 0
If noOfRows > 0 Then
noOfColumns = matrix.Split(vbCrLf)(0).Split(" ").Count
End If
If noOfColumns > 0 And noOfRows > 0 Then
Dim ret(noOfRows, noOfColumns) As Integer
Dim lines As String() = matrix.Split(vbCrLf)
Dim row As Integer = 0
For Each line As String In lines
Dim col As Integer = 0
line = line.Replace("(", "")
line = line.Replace(")", "")
For Each s As String In line.Split(" ")
ret(row, col) = Integer.Parse(s)
col += 1
Next
row += 1
Next
Return ret
Else
Return Nothing
End If
End Function
This outputs:
0,0=1
0,1=2
0,2=3
1,0=4
1,1=5
1,2=6
Actually, I want to do this to detect the value inside the rounding bracket and do the rounding to whatever inside the rounding bracket. For example:
Dim h As String = "ROUNDING(30.98998(10))*2+3"
Dim r As String = h.ToString.Substring(h.ToString.IndexOf("ROUNDING(") + 1, h.ToString.IndexOf(")") - 1 - h.ToString.IndexOf("ROUNDING("))
In this case, after the ROUNDING( there is one more ( and ). How to make the open bracket on the ROUNDING to match to the end of it's closing bracket?
Thanks in advance!
You could use the following ReadInBetweenSameDepth Function.
Public Function ReadInBetweenSameDepth(str As String, delimiterStart As Char, delimiterEnd As Char) As String
If delimiterStart = delimiterEnd OrElse String.IsNullOrWhiteSpace(str) OrElse str.Length <= 2 Then
Return Nothing
End If
Dim delimiterStartFound As Integer = 0
Dim delimiterEndFound As Integer = 0
Dim posStart As Integer = -1
For i As Integer = 0 To str.Length - 1
If str(i) = delimiterStart Then
If i >= str.Length - 2 Then
'delimiter start is found in any of the last two characters
Return Nothing
End If
'it means, there isn't anything in between the two
If delimiterStartFound = 0 Then
'first time
posStart = i + 1
End If
'assign the starting position only the first time...
'increase the number of delimiter start count to get the same depth
delimiterStartFound += 1
End If
If str(i) = delimiterEnd Then
delimiterEndFound += 1
If delimiterStartFound = delimiterEndFound AndAlso i - posStart > 0 Then
Return str.Substring(posStart, i - posStart)
'only successful if both delimiters are found in the same depth
End If
End If
Next
Return Nothing
End Function
It basically checks if the delimiters (such as ( and ) ) are in the same "depth".
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
Hi I'm trying to get the number of occurrences of a character out of a txtbox. Still haven't found the answer...
For example:
I give in a sentence... "Hello there!." and in a listbox there must be...
H - 2 times
e - 3 times
....
this is my code...
For i = 0 To txtSent.Text.Length - 1
If (Char.IsLetter(txtSent.Text(i))) Then
Dim str = Len(txtSent.Text) - Len(Replace(txtSen.Text, txtSen.Text(i), ""))
lstOutput.Items.Add(txtZin.Text(i) & " occurs " & str & " time(s)")
End If
Next´
But i need it to be "m - 5" instead of repeating all the characters of "m"
Can you help me?
Take a look at this article. Does exactly what you are after. http://msdn.microsoft.com/en-us/library/bb397940.aspx
This is a method in vb.net that should help you aswell.
Public Function GetNumSubstringOccurrences(ByVal text As String, ByVal search As String) As Integer
Dim num As Integer = 0
Dim pos As Integer = 0
If Not String.IsNullOrEmpty(text) AndAlso Not String.IsNullOrEmpty(search) Then
While text.IndexOf(search.ToLower(), pos) > -1
num += 1
pos = text.ToLower().IndexOf(search.ToLower(), pos) + search.Length + 1
End While
End If
Return num
End Function
To loop the alphabet, do the following
Dim s As String = "ssssddfffccckkkllkeeiol"
For Each c In "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray()
Console.WriteLine(GetNumSubstringOccurrences(s, c))
Next
I am have written the following code:
Dim i As Integer
Dim pos As Integer = 0
Dim neg As Integer = 0
Dim zer As Integer = 0
Dim TextBoxes() As String = {Val(TextBox1.Text), Val(TextBox2.Text),
Val(TextBox3.Text), Val(TextBox4.Text),
Val(TextBox5.Text), Val(TextBox6.Text),
Val(TextBox7.Text), Val(TextBox8.Text),
Val(TextBox9.Text), Val(TextBox10.Text)}
For i = 0 To 9
If TextBoxes(i) > 0 Then
pos += 1
End If
If TextBoxes(i) < 0 Then
neg += 1
End If
If TextBoxes(i) = 0 Then
zer += 1
End If
Next i
Label4.Text = (pos)
Label5.Text = (neg)
Label6.Text = (zer)
When the program executes and I put some values into the text boxes, the output looks like this. The first text box contains 1 which is positive and the other one contains -1 which is negative. It's working well.
The problem occurs here: the program is counting the empty boxes as 0 and displaying 8 in the total number of zeros. All of the other 8 text boxes were left blank. How can I Fix the issue so that it doesn't count the empty text boxes as 0.
For reference, here is my related, previous problem which has already been solved: Finding String of Substring in VB without using library function
The problem is that you are calling the Val function to get the value in each text box. Val returns 0 if the given text is empty or non-numeric. If you want to check that, you should just store the original strings in the array and then check the value in the loop, like this:
Dim i As Integer
Dim pos As Integer = 0
Dim neg As Integer = 0
Dim zer As Integer = 0
Dim TextBoxes() As String = {TextBox1.Text, TextBox2.Text,
TextBox3.Text, TextBox4.Text,
TextBox5.Text, TextBox6.Text,
TextBox7.Text, TextBox8.Text,
TextBox9.Text, TextBox10.Text}
For i = 0 To 9
If TextBoxes(i) <> String.Empty Then
If Val(TextBoxes(i)) > 0 Then
pos += 1
End If
If Val(TextBoxes(i)) < 0 Then
neg += 1
End If
If Val(TextBoxes(i)) = 0 Then
zer += 1
End If
End If
Next i
Label4.Text = pos.ToString()
Label5.Text = neg.ToString()
Label6.Text = zer.ToString()
However, the Val function is mainly just provided for backwards compatibility with VB6. It will work, but I would recommend using Integer.TryParse instead. Note that I also added ToString to the last three lines. As others have mentioned, it would behoove you to turn Option Strict On.