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
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
I am having a problem where I just can't seem to get it to split or even display the message. The message variable is predefined in another part of my code and I have debugged to make sure that the value comes through. I am trying to get it so that every 100 characters it goes onto a new line and with every message it also goes onto a new line.
y = y - 13
messagearray.AddRange(Message.Split(ChrW(100)))
Dim k = messagearray.Count - 1
Dim messagefin As String
messagefin = ""
While k > -1
messagefin = messagefin + vbCrLf + messagearray(k)
k = k - 1
End While
k = 0
Label1.Text = Label1.Text & vbCrLf & messagefin
Label1.Location = New Point(5, 398 + y)
You can use regular expression. It will create the array of strings where every string contains 100 characters. If the amount of remained characters is less than 100, it will match all of them.
Dim input = New String("A", 310)
Dim mc = Regex.Matches(input, ".{1,100}")
For Each m As Match In mc
'// Do something
MsgBox(m.Value)
Next
You can use LINQ to do that.
When you do a Select you can get the index of the item by including a second parameter. Then group the characters by that index divided by the line length so, the first character has index 0, and 0 \ 100 = 0, all the way up to the hundredth char which has index 99: 99 \ 100 = 0. The next hundred chars have 100 \ 100 = 1 to 199 \ 100 = 1, and so on (\ is the integer division operator in VB.NET).
Dim message = New String("A"c, 100)
message &= New String("B"c, 100)
message &= New String("C"c, 99)
Dim lineLength = 100
Dim q = message.Select(Function(c, i) New With {.Char = c, .Idx = i}).
GroupBy(Function(a) a.Idx \ lineLength).
Select(Function(b) String.Join("", b.Select(Function(d) d.Char)))
TextBox1.AppendText(vbCrLf & String.Join(vbCrLf, q))
It is easy to see how to change the line length because it is in a variable with a meaningful name, for example I set it to 50 to get the output
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
You can use String.SubString to do that. Like this
Dim Message As String = "your message here"
Dim MessageList As New List (Of String)
For i As Integer = 0 To Message.Length Step 100
If (Message.Length < i + 100) Then
MessageList.Add(Message.SubString (i, Message.Length - i)
Exit For
Else
MessageList.Add(Message.SubString (i, 100))
End If
Next
Dim k = MessageList.Count - 1
...
Here is what your code produced with a bit of clean up. I ignored the new position of the label.
Private Sub OpCode()
Dim messagearray As New List(Of String) 'I guessed that messagearray was a List(Of T)
messagearray.AddRange(Message.Split(ChrW(100))) 'ChrW(100) is lowercase d
Dim k = messagearray.Count - 1
Dim messagefin As String
messagefin = ""
While k > -1
messagefin = messagefin + vbCrLf + messagearray(k)
k = k - 1
End While
k = 0 'Why reset k? It falls out of scope at End Sub
Label1.Text = Label1.Text & vbCrLf & messagefin
End Sub
I am not sure why you think that splitting a string by lowercase d would have anything to do with getting 100 characters. As you can see the code reversed the order of the list items. It also added a blank line between the existing text in the label (In this case Label1) and the new text.
To accomplish your goal, I first created a List(Of String) to store the chunks. The For loop starts at the beginning of the input string and keeps going to the end increasing by 10 on each iteration.
To avoid an index out of range which would happen at the end. Say, we only had 6 characters left from start index. If we tried to retrieve 10 characters we would have an index out of range.
At the end we join the elements of the string with the separated of new line.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
BreakInto10CharacterChunks("The quick brown fox jumped over the lazy dogs.")
End Sub
Private Sub BreakInto10CharacterChunks(input As String)
Dim output As New List(Of String)
Dim chunk As String
For StartIndex = 0 To input.Length Step 10
If StartIndex + 10 > input.Length Then
chunk = input.Substring(StartIndex, input.Length - StartIndex)
Else
chunk = input.Substring(StartIndex, 10)
End If
output.Add(chunk)
Next
Label1.Text &= vbCrLf & String.Join(vbCrLf, output)
End Sub
Be sure to look up String.SubString and String.Join to fully understand how these methods work.
https://learn.microsoft.com/en-us/dotnet/api/system.string.substring?view=netframework-4.8
and https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=netframework-4.8
I very much want to count the values in a multiline textbox each time each value appears in descending order> in ascending order. I tried a lot but nothing works as it should. (VB.Net)
Textbox1.Lines
2
3
2
2
4
7
7
7
28
28
Expected Output: Textbox2.Lines
2 = Count = 3
7 = Count = 3
28 = Count = 2
3 = Count = 1
4 = Count = 1
What i try and dind't worked.
#1
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
End If
Next
Return cnt
End Function
#2
Dim a As String = "this is test"
Dim pattern As String = "t"
Dim ex As New System.Text.RegularExpressions.Regex(pattern)
Dim m As System.Text.RegularExpressions.MatchCollection
m = ex.Matches(a)
MsgBox(m.Count.ToString())
#3
Public Shared Function StrCounter(str As String, CountStr As String) As Integer
Dim Ctr As Integer = 0
Dim Ptr As Integer = 1
While InStr(Ptr, str, CountStr) > 0
Ptr = InStr(Ptr, str, CountStr) + Len(CountStr)
Ctr += 1
End While
Return Ctr
End Function
You need to remember which strings have already appeared and then count them. To do that, you can use a dictionary.
Dim dict_strCount As Dictionary(Of String, Integer) = New Dictionary(Of String, Integer)()
' Run over each line in the input
For Each line As String In tb_yourTextBox.Text.Lines
' Check if we have already counted the string in this line
If dict_strCount.ContainsKey(line) Then
dict_strCount(line) += 1 ' if so, increment that count
Else
dict_strCount.Add(line, 1) ' if not, add it to the dictionary (with count of 1)
End If
Next
tb_yourOutputTextBox.Text = String.Empty ' clear the output
' run over all the elements in the dictionary in ascending order by value
' and output to the output textbox
For Each kvp As KeyValuePair(Of String, Integer) In dict_strCount.OrderBy(Function(x) x.Value)
tb_yourOutputTextBox.Text += kvp.Key & ": " & kvp.Value.ToString() & vbNewLine
Next
You may test it here
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 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