How can put split integers in a two-dimensional array? - vb.net

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

Related

Splitting string every 100 characters not working

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

Count a specific string in a multiline textbox (VB.Net)

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

how to convert (3 digit) Decimal to Ascii from textbox.text?

when i inpot Decimal numbers to textbox, the output will be one word
EX:
input:
textbox.text = 11311711511597105
output:
textbox.text = qussai
You should show us what you had tried.
The full code should be like this:
Module VBModule
Sub Main()
Dim output As String = DecimalToASCII("113117115115097105")
Console.WriteLine(output)
End Sub
Function DecimalToASCII(ByVal input As String) As String
Dim current As String = ""
Dim temp As Integer = 0
If input.Length Mod 3 <> 0 Then
Return "Wrong Input"
End If
For i As Integer = 0 To input.Length - 1 Step 3
temp = 0
For j As Integer = i To i + 2
temp *= 10
temp += CType(input(j).ToString(), Integer)
Next
current &= Chr(temp).ToString()
Next
Return current
End Function
End Module

Get the number of occurrences out of textbox

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

VB 2008 (Console) "For Each Loop" Lottery Results Comparison

I am facing an issue to perform numbers comparison between the integers inputted by user and random numbers generated by the codes.
Each of the integers input by the user should then be compared with the LOTTO numbers to check for a match. A For each… loop needs to be used to achieve this.
After checking all the 7 user input integers against the LOTTO numbers, the total number of matches should be output to the user. If there are no matches the output should read “LOOSER!”.
Here are my codes, I'm currently only stuck at the comparison portion, and we need to use for each loop to achieve this.
Imports System
Module Lotto
Sub Main()
'Declaration
Dim numbers(6) As Integer
Dim IsStarted As Boolean = True
'Prompt user to enter
Console.WriteLine("Please enter your 7 lucky numbers from 0 - 9 ONLY")
'Use Do While Loop to re-iterate the prompts
Do While IsStarted
For pos As Integer = 0 To 6
Console.Write("Enter number {0}: ", pos + 1)
'How it stores into an array
numbers(pos) = Console.ReadLine()
'Check if it is a number: use IsNumberic()
If IsNumeric(numbers(pos)) Then 'proceed
'Check if it is NOT 0 < x > 9
If numbers(pos) < 0 Or numbers(pos) > 9 Then
'Don't proceed
Console.WriteLine("Invalid Input")
IsStarted = True
'When any number is invalid, exit the loop
Exit For
End If
End If
IsStarted = False
Next
Loop
'Printing out the array. It can also be written as
'For pos = LBound(numbers) To UBound(numbers)
For pos = 0 To 6
Console.Write(numbers(pos) & " ")
Next
Console.WriteLine()
'Random number generator
Randomize()
Dim random_numbers(6) As Integer
Dim upperbound As Integer = 7
Dim lowerbound As Integer = 0
Dim rnd_number As Double = 0
For pos = 0 To 6
rnd_number = CInt((upperbound - lowerbound) * Rnd() + lowerbound)
random_numbers(pos) = rnd_number
Console.Write(random_numbers(pos) & " ")
Next
'Iterate and compare
Dim isSame As Boolean = False
Dim pos2 As Integer = 0
Dim Counter As Integer = 0
'For check = 0 To 6
'If numbers(pos2).Equals(random_numbers(pos2)) Then
For Each number As Integer In numbers
'Console.WriteLine(pos2 + 1 & ":" & number & ":")
If number.Equals(random_numbers(pos2)) Then
'Console.WriteLine("here is the number that matched:" & number & ":")
isSame = True
pos2 = pos2 + 1
End If
For Each num As Integer In random_numbers
If random_numbers Is numbers Then
Counter = Counter + 1
End If
Next
Next
Console.WriteLine()
'Display result
If isSame = True Then
Console.WriteLine("The total numbers of matches are: " & Counter)
Else
Console.WriteLine("LOOSER!")
End If
Console.ReadLine()
End Sub
End Module
Dim intCursor As Integer = 0
For Each intNumber As Integer In numbers
'Assumes first user chosen number must equal
'the first random number to be considered a match,
'the second user number must equal the second random,
'etc (Ordering is a factor).
If random_numbers(intCursor) = intNumber Then
Counter += 1
End If
intCursor += 1
Next
If (Counter > 0) Then
Console.WriteLine("The total numbers of matches are: " & Counter)
Else
Console.WriteLine("LOOSER!")
End If