Convert a subnet mask into binary (octets) in vb.net - vb.net

How can I convert a subnetmask into binary, so I'll end up with 32 digits?
I can convert it into Binary, using Convert.ToString(Long-to-convert, 2)
But a subnetmask of 255.255.255.0 returns(it returns it without the spaces though):
1111 1111 1111 1111 1111 1111 0
When I want it to be:
1111 1111 1111 1111 1111 1111 0000 0000

If you convert each byte separately then before the concatenate step you can do a PadLeft(8, '0') on each value. This would add the missing '0's.

'place this code in a separate module
'originally written by Dewayne Basnett in VBA - 1997
'converted to VB .Net - 2007
Option Strict On : Option Explicit On : Option Infer Off
Imports System.Net, System.Text
Module IP4Stuff
Const IPbrdcst As Long = 4294967295 '255.255.255.255 FF.FF.FF.FF
Dim aIP, aMSK As IPAddress
Dim nIP, nMSK, nNET, nHOST, addrs As Long 'numeric equivalents
Dim nCIDR, CIDR, x, y As Integer
Const shBits As Boolean = True 'True = show debug with bits using showBits function
Public Function ipRange(ByVal ipAddr As String, _
ByVal ipMask As String) As List(Of String)
'returns a list of all ip addresse on a given network
'
'ipRange("192.168.3.133", "255.255.254.0") '512 hosts - octet crossing
'
'255.255.254.0 is /23
'List(Of String) - partial output
'192.168.2.0
'192.168.2.1
'192.168.2.2
'...
'192.168.2.254
'192.168.2.255
'192.168.3.0
'192.168.3.1
'...
'192.168.3.253
'192.168.3.254
'192.168.3.255
'note
'first entry in list is THE network number
'last entry in list is the directed broadcast
'
nMSK = IPasNum(ipMask) 'get the Mask as number
CIDR = nCIDR 'get CIDR
nIP = IPasNum(ipAddr) 'get the IP address as number
nNET = IPnetAsNum(nIP, nMSK) 'get THE network number as number
addrs = nNET 'addrs = THE network number as number
nHOST = IPnumOfHosts(nMSK) 'get the number of hosts
If shBits Then
Debug.WriteLine("")
Debug.WriteLine("IP".PadRight(10, " "c) & showBits(nIP) & " " & ipAddr)
Debug.WriteLine("Mask".PadRight(10, " "c) & showBits(nMSK) & " " & ipMask)
Debug.WriteLine("Net".PadRight(10, " "c) & showBits(nNET) & " " & NumToIp(nNET))
Debug.WriteLine("Hosts".PadRight(10, " "c) & showBits(nHOST) & " " & nHOST.ToString)
Debug.WriteLine("CIDR".PadRight(10, " "c) & CIDR.ToString)
'Stop
End If
If nIP < 0 OrElse nMSK < 0 OrElse nNET = 0 OrElse nHOST = 0 Then
Return New List(Of String) 'error
End If
ipRange = New List(Of String)
For x As Long = 0 To nHOST
ipRange.Add(NumToIp(addrs)) 'add host to list
addrs += 1 'increment it
Next
End Function
Public Function IPnets(ByVal ipAddr As String, _
ByVal curCIDR As Integer, _
ByVal newCIDR As Integer) As List(Of String)
'returns a list of sub-nets using any IP in the current network,
'the current mask as CIDR and new mask as CIDR.
'192.168.3.? /23 to /25 - octet crossing
'
'IPnets("192.168.3.128", 23, 25)
'
'List(Of String)
'255.255.255.128
'192.168.2.0
'192.168.2.128
'192.168.3.0
'192.168.3.128
'
Dim curMASK, newMASK, netPlus1 As Long, numOfNets As Integer
nIP = IPasNum(ipAddr) 'get the IP address as number
If nIP < 0 OrElse curCIDR < 2 OrElse curCIDR > newCIDR OrElse newCIDR > 30 Then
Return New List(Of String) 'error
End If
IPnets = New List(Of String)
curMASK = MaskFromCidr(curCIDR) 'convert CIDR's to mask as number
newMASK = MaskFromCidr(newCIDR)
nHOST = IPnumOfHosts(newMASK)
netPlus1 = nHOST + 1 'used to add 1 to the network portion of the ip address
nNET = IPnetAsNum(nIP, curMASK) 'get THE network number as number
numOfNets = CInt(2 ^ (newCIDR - curCIDR)) 'number of networks
IPnets.Add(NumToIp(newMASK)) '<<<<<<<<<<<<<<<<<<<<< first entry in list is the new mask
If shBits Then
Debug.WriteLine("")
Debug.WriteLine("IP".PadRight(10, " "c) & showBits(nIP) & " " & ipAddr)
Debug.WriteLine("Network".PadRight(10, " "c) & showBits(nNET) & " " & NumToIp(nNET))
Debug.WriteLine("Cur. Mask".PadRight(10, " "c) & showBits(curMASK) & " " & NumToIp(curMASK))
Debug.WriteLine("New Mask".PadRight(10, " "c) & showBits(newMASK) & " " & NumToIp(newMASK))
Debug.WriteLine("Plus 1".PadRight(10, " "c) & showBits(netPlus1) & " " & NumToIp(netPlus1))
Debug.WriteLine("Num. Nets".PadRight(10, " "c) & numOfNets.ToString)
'Stop
End If
For x As Integer = 0 To numOfNets - 1
IPnets.Add(NumToIp(nNET))
'to get last address(broadcast) Dim BrdCst as long = nNET Or nHOST
nNET += netPlus1 'add one network number
Next
End Function
Private Function MaskFromCidr(ByVal CIDR As Integer) As Long
'x = 32 - CIDR
'z = (2^x)-1
'return z xor 255.255.255.255
MaskFromCidr = CLng(2 ^ ((32 - CIDR)) - 1) Xor IPbrdcst
End Function
Private Function IPnumOfHosts(ByVal IPmsk As Long) As Long 'a mask for the host portion
'255.255.255.0 XOR 255.255.255.255 = 255 so 0 to 255 is 256 hosts
IPnumOfHosts = IPmsk Xor IPbrdcst 'cacluate the number of hosts
End Function
Private Function IPnetAsNum(ByVal IPnum As Long, ByVal IPmsk As Long) As Long 'extract network from ip address
'192.168.2.113 AND 255.255.255.0 = 192.168.2.0
IPnetAsNum = IPnum And IPmsk 'calculate THE network number
End Function
Private Function IPasNum(ByVal AipAddr As String) As Long 'return -1 on error
If Not IPAddress.TryParse(AipAddr, aIP) Then 'convert string to IP
Return -1 'error
Else
IPasNum = IPtoNum(aIP) 'convert IP to number
If IPasNum = 0 Then
Return -1 'error
End If
End If
End Function
Private Function IPtoNum(ByVal theIP As IPAddress) As Long 'convert IP to number
Dim IPb() As Byte = theIP.GetAddressBytes 'get the octets
Dim theBit As Integer = 31 'work MSb to LSb
Dim addr As Long 'accumulator for address
nCIDR = 0
For x = 0 To 3 'four octets
For y = 7 To 0 Step -1 'with 8 bits each - duh
If (IPb(x) And CByte(2 ^ y)) = CByte(2 ^ y) Then 'if the bit is on
addr += CLng(2 ^ theBit) 'accumulate
nCIDR += 1 'count bits
End If
theBit -= 1 'decrement bit pos
Next
Next
Return addr
End Function
Private Function NumToIp(ByVal theIP As Long) As String 'convert number back to IP
Dim IPb(3) As Byte '4 octets
Dim theBit As Integer = 31 'work MSb to LSb
Dim addr As String 'accumulator for address
For x = 0 To 3 'four octets
For y = 7 To 0 Step -1 '8 bits
If (theIP And CLng(2 ^ theBit)) = CLng(2 ^ theBit) Then 'if the bit is on
IPb(x) += CByte(2 ^ y) 'accumulate
End If
theBit -= 1
Next
addr &= IPb(x).ToString & "." 'add current octet to string
Next
Return addr.TrimEnd("."c)
End Function
Private Function showBits(ByVal aNum As Long) As String
Dim strObits As New StringBuilder
strObits.Append(Convert.ToString(aNum, 2).PadLeft(32, "0"c))
For ix As Integer = 24 To 0 Step -8
strObits.Insert(ix, " ")
Next
showBits = strObits.ToString.Trim
End Function
End Module

Related

wmi. Find out the model and size of the hard drive

Good day!
There is the following function, with which I display information from certain wmi classes.
Private Function GetDetails(ByVal pcname As String, ByVal ClassName As String, ByVal Selection As String) As String
Dim tmpstr As String = ""
Dim myScope As New ManagementScope("\\" & pcname & "\root\cimv2")
Dim oQuery As New SelectQuery("SELECT * FROM " & ClassName)
Dim oResults As New ManagementObjectSearcher(myScope, oQuery)
For Each queryObj As ManagementObject In oResults.Get()
Try
tmpstr = queryObj(Selection)
Catch ex As Exception
tmpstr = ""
MsgBox(ex.Message)
End Try
Next
Return tmpstr
End Function
That's how I use it.
Dim HardDriveName As String = GetDetails(PC, "Win32_DiskDrive", "Caption")
Dim HardDriveSize As String = GetDetails(PC, "Win32_DiskDrive", "Size")
The problem arises in the fact that several hard drives can be installed on a PC. Tell me how to display information on all hard drives?
I understand that you need to use a loop. But I don't understand how to do it. Thanks for the help.
I found this solution for myself:
Private Sub HardInfo(ByVal pcname As String)
Dim myScope As New ManagementScope("\\" & pcname & "\root\cimv2")
Dim oQuery As New SelectQuery("SELECT * FROM Win32_DiskDrive")
Dim searcher As New ManagementObjectSearcher(myScope, oQuery)
Dim i As Integer
For Each drive As ManagementObject In searcher.Get()
i += 1
MsgBox("Hard # " & i, drive("Caption") & "(" & Reformat_TB_GB_MB(drive("Size")) & ")")
Next drive
End Sub
' Reformat as TB, GB or MB (if needed)
Private Function Reformat_TB_GB_MB(ByRef Value As Long)
If Len(Value.ToString) > 12 Then ' Reformat if TB
Return Format(Value / 1024 / 1024 / 1024 / 1024, "##0.00 TB")
ElseIf Len(Value.ToString) > 9 Then ' Reformat if GB
Return Format(Value / 1024 / 1024 / 1024, "###,##0.00 GB")
ElseIf Len(Value.ToString) > 6 Then ' Reformat if MB
Return Format(Value / 1024 / 1024, "###,###,##0.00 MB")
ElseIf Len(Value.ToString) > 3 Then ' Reformat if KB
Return Format(Value / 1024, "###,###,###,##0.00 KB")
Else
Return Format(Value, "###,###,###,###,##0.00 Bytes")
End If
End Function

Converting SHA-2 hash into alphanumeric hash (vb.net)

I have SHA-2 hash values. Here's an example:
qlbQbEd8khe2vEYG9acKScUiVTC6y1UorkMvptATwwxkVApkOCUH7hwkncbi2TY78HrIeC19G8EHlaAmj6sBAwCxhF2TeOpmJ1+2OfbfXF+jMWUO74O7WHJuwoq+R5aKa0c2QYbyrcd/DWSprdkrF1gyz+RWVXYQug63aAhC0j0=
I need to convert these into an alphanumeric hash — that is, using only capital letters and numbers ("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"). The process has to be reversible for SHA-2 hash comparison.
The reason for this conversion is aesthetics. The resulting hash will be used as a license key, and has to be shorter and more easily readable and typeable.
I read that I could try to re-encode that hash into Base36, but I have been unsuccessful. Can anyone give any suggestions?
This code is an example for converting Base36 to/from Base26
Const Base36 As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Const Base26 As String = "abcdefghijklmnopqrstuvwxyz"
Function Num2Base(Vlu As Long, Base As String) As String
Dim A() As Integer = Nothing
Dim y As Integer = -1
Dim X As Long = Vlu
Dim Ln As Integer = Base.Length
Do While X > -1
y = y + 1
ReDim Preserve A(y)
A(y) = X Mod Ln
X = ((X - A(y)) / Ln) - 1
Loop
Dim res As String = ""
If y >= 0 Then
For Each d As Integer In A
res &= Mid(Base, d + 1, 1)
Next
End If
Return res
End Function
Function Base2Num(s As String, Base As String) As Long
If s.Length = 0 Then
Throw New Exception("'S' can not be empty")
End If
Dim res As Long = -1
Dim Ln As Integer = Base.Length
Dim x As Integer = 0
For Each c In s
res += (Base.IndexOf(c) + 1) * (Ln ^ x)
x += 1
Next
Return res
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim Num As Long = 1313
Dim b36 As String = Num2Base(Num, Base36) 'convert Num to base36
Dim b26 As String = Num2Base(Num, Base26) 'convert Num to base26
MessageBox.Show("Num:" & Num & vbCrLf & "ToBase36:" & b36 & vbCrLf & "ToBase26:" & b26, "Message 1")
Dim N36 As Long = Base2Num(b36, Base36) 'convert Base36 to Num
Dim N26 As Long = Base2Num(b26, Base26) 'convert Base26 to Num
MessageBox.Show("N36:" & N36 & vbCrLf & "N26:" & N26, "Message 2")
b26 = Num2Base(Base2Num(b36, Base36), Base26) 'convert Base36 to Base 26
MessageBox.Show("Base36 to Base 26 :" & b26, "Message 3")
b36 = Num2Base(Base2Num(b26, Base26), Base36) 'convert Base26 to Base 36
MessageBox.Show("Base26 to Base 36 :" & b36, "Message 4")
MessageBox.Show(Num2Base(1486154465904653, Base36), "Message 5")
End Sub
Unfortunately this code can not work with long strings(more than 12 chrs) due the limitation of the type Long,so you may need to split SHA-2 string to small parts

Value Of Type Form1.Data cannot be converted to Form1.Data() when passing parameters

At the start of the program I define a new Public Structure 'Data':
Public Structure Data
Dim car, grid, points As String
Dim driver, team, fastestlap, racetime As String
End Structure
I then have the user input data and it is added to array displayData(5) of data type 'Data'.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim displayData(5) As Data
Dim accepted As Boolean = False
Dim temp As String
Dim tempNum As Integer
Dim output As String = ""
Dim arraysize As Integer = 0
For x = 0 To 5
displayData(x).driver = InputBox("Please enter the name of driver number " & x + 1)
temp = InputBox("Please enter the car number of driver number " & x + 1)
While accepted = False
If IsNumeric(temp) Then
accepted = True
displayData(x).car = temp
Else
accepted = False
temp = InputBox("Error: integer not entered. Please enter the car number of driver number " & x + 1)
End If
End While
accepted = False
displayData(x).team = InputBox("Please enter the team name of driver number " & x + 1)
temp = InputBox("Please enter the grid number of driver number " & x + 1)
tempNum = Convert.ToInt32(temp)
While accepted = False
If IsNumeric(tempNum) Then
accepted = True
displayData(x).grid = temp
Else
accepted = False
temp = InputBox("Error: integer not entered. Please enter the grid number of driver number " & x + 1)
tempNum = Convert.ToInt32(temp)
End If
End While
accepted = False
displayData(x).fastestlap = InputBox("Please enter the fastest lap of driver number " & x + 1)
displayData(x).racetime = InputBox("Please enter the race time of driver number " & x + 1)
temp = InputBox("Please enter the points of driver number " & x + 1)
While accepted = False
If IsNumeric(temp) Then
accepted = True
displayData(x).points = temp
Else
accepted = False
temp = InputBox("Error: integer not entered. Please enter the points of driver number " & x + 1)
End If
End While
accepted = False
output = output & displayData(x).driver & "," & displayData(x).car & "," & displayData(x).team & "," & displayData(x).grid & "," & displayData(x).fastestlap & "," & displayData(x).racetime & "," & displayData(x).points & vbCrLf
Next
Dim filename As String = "U:\Subjects\Computing\AH Computing\Project Files\Leaderboard.csv"
My.Computer.FileSystem.WriteAllText(filename, output, True)
bubbleSort(arraysize, displayData(6))
End Sub
Above is the main bulk of my code. I am getting an error from typing in displayData(6) into bubblesort, which is defined here:
Public Sub bubbleSort(ByVal arraysize As Integer, ByVal displayData() As Data)
Dim counter As Integer
Dim outerloop As Integer
For outerloop = (arraysize - 2) To 0 Step -1
For counter = 0 To outerloop
If displayData(counter).racetime > displayData(counter + 1).racetime Then
swap(displayData(counter).racetime, displayData(counter + 1).racetime)
swap(displayData(counter).car, displayData(counter + 1).car)
swap(displayData(counter).driver, displayData(counter + 1).driver)
swap(displayData(counter).points, displayData(counter + 1).points)
swap(displayData(counter).team, displayData(counter + 1).team)
swap(displayData(counter).fastestlap, displayData(counter + 1).fastestlap)
swap(displayData(counter).grid, displayData(counter + 1).grid)
End If
Next
Next
End Sub
And apparently I need more normal text in order to save this. The bubble sort uses a swap algorithm that I defined in another part of the program, but it is incredibly simple and is 100% not the cause of the error so it seems unproductive to include it.

Conditionally exit or continue the loop in vb.net

I have the following sub below. What it does is that it takes the input from the textbox that the user enters, substitute each letter with a specific numeric value, display the total for each word and then the total for the entire input. For example, if the user types aa bbb e, the output in txtbox5 is:
aa = 40
bbb = 90
e = 40
Total 170
That works fine if the user inputs one long sentence. So I want to calculate each sentence separately in the same fashion and the delimiter for the sentence could be a period or comma. If the user types aa bbb. ff ee. The output should
aa = 40
ccc = 90
Total for the 1st sentence = 120
ff = 100
ee = 80
Total for the 2nd sentence = 180
and so forth
Private Sub Calculate(ByVal input As String)
Dim total As Integer = 0
Dim wordTotal As Integer
Dim dicLetters As New Dictionary(Of Char, Integer)
dicLetters.Add("A", 20)
dicLetters.Add("B", 30)
dicLetters.Add("E", 40)
dicLetters.Add("F", 50)
Dim charValue As Integer
For Each word As String In input.Split(New Char() {" "})
wordTotal = 0
For Each character As Char In word
wordTotal += If(dicLetters.TryGetValue(character, charValue) = _
True, dicLetters(character), 0)
Next
total += wordTotal
txtBox5.Text += word.PadRight(12) + " = " + _
wordTotal.ToString().PadLeft(5) + vbNewLine
Next
txtBox5.Text += "Total:".PadRight(12) + " = " + _
total.ToString().PadLeft(5)
End Sub
Use the Split method to create an array of sentences. It will accept an array of delimiters. Iterate through the array and pass each sentence and the index of the sentence, to your sub routine. In your sub routine add an integer argument to use as the sentence number, and change the output string.
Something like this:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Sentences() As String = TextBox1.Text.Split({","c,"."c})
For I = 0 to Sentences.Count-1
Calculate(Sentences(I), I+1)
Next
End Sub
Private Sub Calculate(ByVal input As String, ByVal index As Integer)
Dim total As Integer = 0
Dim wordTotal As Integer
Dim dicLetters As New Dictionary(Of Char, Integer)
dicLetters.Add("A", 20)
dicLetters.Add("B", 30)
dicLetters.Add("E", 40)
dicLetters.Add("F", 50)
Dim charValue As Integer
For Each word As String In input.Split(New Char() {" "})
wordTotal = 0
For Each character As Char In word
wordTotal += If(dicLetters.TryGetValue(character, charValue) = _
True, dicLetters(character), 0)
Next
total += wordTotal
txtBox5.Text += word.PadRight(12) + " = " + _
wordTotal.ToString().PadLeft(5) + vbNewLine
Next
txtBox5.Text += "Total for sentence " + index.ToString +" :" + " = " + _
total.ToString().PadLeft(5)
End Sub

Finding String of Substring in VB without using library function

I am little bit confused in this program.
I am new to Visual Basic but intermediate to C.
Actually I want to get sub-string of string without using library function of Visual Basic.
Here is the C source code I also given my VB code too.
1.The Program will get two inputs from user i.e A & B
2. Than Find the substring from B.
3. Finally Print the result.
int i,j=0,k=0,substr=0;
for(i=0;i<strlen(a);i++)
{
if(a[i]==b[j])
{
j++;
if(b[j]==0)
{
printf("second string is substring of first one");
substr=1;
break;
}
}
}
for(i=0;i<strlen(b);i++)
{
if(b[i]==a[k])
{
k++;
if(a[k]==0)
{
printf(" first string is substring of second string");
substr=1;
break ;
}
}
}
if(substr==0)
{
printf("no substring present");
}
While my code is
Dim a As String
Dim b As String
a = InputBox("Enter First String", a)
b = InputBox("Enter 2nd String", b)
Dim i As Integer
Dim j As Integer = 0
Dim k As Integer = 0
Dim substr As Integer = 0
For i = 0 To a.Length - 1
If a(i) = b(j) Then
j += 1
If b(j) = 0 Then
MsgBox("second string is substring of first one")
substr = 1
Exit For
End If
End If
Next i
For i = 0 To b.Length - 1
If b(i) = a(k) Then
k += 1
If a(k) = 0 Then
MsgBox(" first string is substring of second string")
substr = 1
Exit For
End If
End If
Next i
If substr = 0 Then
MsgBox("no substring present")
End If
End Sub
While compiling it gives following debugging errors.
Line Col
Error 1 Operator '=' is not defined for types 'Char' and 'Integer'. 17 24
Error 2 Operator '=' is not defined for types 'Char' and 'Integer'. 27 24
Part of your confusion is that .Net strings are much more than just character buffers. I'm going to assume that you can at least use strings. If you can't, use need to declare character arrays instead. That out of the way, this should get you there as a 1:1 translation:
Private Shared Function search(ByVal a As String, ByVal b As String) As Integer
Dim i As Integer = 0
Dim j As Integer = 0
Dim firstOcc As Integer
While i < a.Length
While a.Chars(i)<>b.Chars(0) AndAlso i < a.Length
i += 1
End While
If i >= a.Length Then Return -1 'search can not continue
firstOcc = i
While a.Chars(i)=b.Chars(j) AndAlso i < a.Length AndAlso j < b.Length
i += 1
j += 1
End While
If j = b.Length Then Return firstOcc
If i = a.Length Then Return -1
i = firstOcc + 1
j = 0
End While
Return 0
End Function
Shared Sub Main() As Integer
Dim a As String
Dim b As String
Dim loc As Integer
Console.Write("Enter the main string :")
a = Console.ReadLine()
Console.Write("Enter the search string :")
b = Console.ReadLine()
loc = search(a, b)
If loc = -1 Then
Console.WriteLine("Not found")
Else
Console.WriteLine("Found at location {0:D}",loc+1)
End If
Console.ReadKey(True)
End Sub
But please don't ever actually use that. All you really need is this:
Private Shared Function search(ByVal haystack as String, ByVal needle As String) As Integer
Return haystack.IndexOf(needle)
End Function
VB has a built-in function called InStr, it's part of the language. It returns an integer specifying the start position of the first occurrence of one string within another.
http://msdn.microsoft.com/en-us/library/8460tsh1(v=VS.80).aspx
Pete
Try this one, this will return a List(Of Integer) containing the index to all occurrence's of the find text within the source text, after the specified search starting position.
Option Strict On
Public Class Form1
''' <summary>
''' Returns an array of indexes where the find text occurred in the source text.
''' </summary>
''' <param name="Source">The text you are searching.</param>
''' <param name="Find">The text you are searching for.</param>
''' <param name="StartIndex"></param>
''' <returns>Returns an array of indexes where the find text occurred in the source text.</returns>
''' <remarks></remarks>
Function FindInString(Source As String, Find As String, StartIndex As Integer) As List(Of Integer)
If StartIndex > Source.Length - Find.Length Then Return New List(Of Integer)
If StartIndex < 0 Then Return New List(Of Integer)
If Find.Length > Source.Length Then Return New List(Of Integer)
Dim Results As New List(Of Integer)
For I = StartIndex To (Source.Length) - Find.Length
Dim TestString As String = String.Empty
For II = I To I + Find.Length - 1
TestString = TestString & Source(II)
Next
If TestString = Find Then Results.Add(I)
Next
Return Results
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim Search As String = "Hello world, this world is an interesting world"
Dim Find As String = "world"
Dim Indexes As List(Of Integer) = New List(Of Integer)
Try
Indexes = FindInString(Search, Find, 0)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
RichTextBox1.Text = "Search:" & vbCrLf
RichTextBox1.Text = RichTextBox1.Text & Search & vbCrLf & vbCrLf
RichTextBox1.Text = RichTextBox1.Text & "Find:" & vbCrLf
RichTextBox1.Text = RichTextBox1.Text & Find & vbCrLf & vbCrLf
RichTextBox1.Text = RichTextBox1.Text & "-----------" & vbCrLf
RichTextBox1.Text = RichTextBox1.Text & "Result Indexes:" & vbCrLf & vbCrLf
For Each i As Integer In Indexes
RichTextBox1.Text = RichTextBox1.Text & i.ToString & vbCr
Next
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
Here is another way, where there is no use of .Net functions.
Function FindInString(Source As String, Find As String, StartIndex As Integer) As Integer()
If StartIndex > Len(Source) - Len(Find) Then Return {}
If StartIndex < 0 Then Return {}
If Len(Find) > Len(Source) Then Return {}
Dim Results As Integer() = {}, ResultCount As Integer = -1
For I = StartIndex To Len(Source) - Len(Find)
Dim TestString As String = ""
For II = I To I + Len(Find) - 1
TestString = TestString & Source(II)
Next
If TestString = Find Then
ResultCount += 1
ReDim Preserve Results(ResultCount)
Results(ResultCount) = I
End If
Next
Return Results
End Function