How to remove the last element from an array in VB.NET. I need to split the street and housenumber.
STREET
Split the address on spaces
Remove last element (missing in the code)
Join array
NUMBER
Split the address on spaces
get last element
My code:
'split address
Dim addressArray() As String = args.Content.Split(" ")
'remove last element and return the joined array
Return String.Join(" ", addressArray.Remove(addressArray.Length() - 1))
Dim foo() As String = "This is a test".Split(New Char() {" "c}, StringSplitOptions.RemoveEmptyEntries)
Array.Resize(foo, foo.Length - 1)
Dim s As String = String.Join(" ", foo)
or use lists
Dim foo As New List(Of String)
foo.AddRange("This is a test".Split(New Char() {" "c}, StringSplitOptions.RemoveEmptyEntries))
foo.RemoveAt(foo.Count - 1)
Dim s As String = String.Join(" ", foo)
As far as using LINQ and performance, judge for yourself
Public Class Form1
'to LINQ or not to LINQ
'judge for yourself
Dim stpw As New Stopwatch
Private Sub Button1_Click(sender As System.Object, _
e As System.EventArgs) Handles Button1.Click
Dim ipsumA() As String = New String() {"Lorem", "ipsum", "dolor", "sit", _
"amet", "consectetur", "adipisicing", _
"elit", "sed", "do", "eiusmod", _
"tempor", "incididunt", "ut", "labore", _
"et", "dolore", "magna", "aliqua", "Ut", _
"enim", "ad", "minim", "veniam", "quis", _
"nostrud", "exercitation", "ullamco", _
"laboris", "nisi", "ut", "aliquip", "ex", _
"ea", "commodo", "consequat", "Duis", "aute", _
"irure", "dolor", "in", "reprehenderit", "in", _
"voluptate", "velit", "esse", "cillum", "dolore", _
"eu", "fugiat", "nulla", "pariatur", "Excepteur", _
"sint", "occaecat", "cupidatat", "non", "proident", _
"sunt", "in", "culpa", "qui", "officia", "deserunt", _
"mollit", "anim", "id", "est", "laborum"}
Const tries As Integer = 100000
Debug.WriteLine("")
stpw.Reset()
stpw.Start()
For x As Integer = 1 To tries
Dim s As String = arrayTake(ipsumA)
Next
stpw.Stop()
Debug.WriteLine(stpw.ElapsedTicks.ToString)
stpw.Reset()
stpw.Start()
For x As Integer = 1 To tries
Dim s As String = arrayRsz(ipsumA)
Next
stpw.Stop()
Debug.WriteLine(stpw.ElapsedTicks.ToString)
End Sub
Private Function arrayRsz(test As String()) As String
Array.Resize(test, test.Length - 1)
Return String.Join(" ", test)
End Function
Private Function arrayTake(test As String()) As String
Return String.Join(" ", test.Take(test.Length - 1))
End Function
End Class
You can't remove items from an array. The size of an array is decided when you create it, and can't be changed.
You can create a result that contains the items from the array except the last one:
Return String.Join(" ", addressArray.Take(addressArray.Length() - 1))
Edit:
If you are concerned about performance, you should not do any Split or Join at all, but simply get the parts of the string using simple string operations:
Dim pos As Integer = args.Content.LastIndexOf(" "C)
Dim street As String = args.Content.Substring(0, pos)
Dim number As String = args.Content.Substring(pos + 1)
This is at least ten times faster than any other method presented here.
Edit 2:
Here is the performance test code (C#):
Dim time As Performance = New Performance(1000000, 6)
Dim address As String = "aölskdjf öawe öofij 42"
Console.WriteLine(time.Take("SplitTakeJoin", Sub()
Dim parts As String() = address.Split(" "c)
Dim street As String = String.Join(" ", parts.Take(parts.Length - 1))
End Sub))
Console.WriteLine(time.Take("SplitResizeJoin", Sub()
Dim parts As String() = address.Split(" "c)
Array.Resize(parts, parts.Length - 1)
Dim street As String = String.Join(" ", parts)
End Sub))
Console.WriteLine(time.Take("Substring", Sub()
Dim street As String = address.Substring(0, address.LastIndexOf(" "c))
End Sub))
Output:
SplitTakeJoin 0,000511 ms.
SplitResizeJoin 0,000323 ms.
Substring 0,000031 ms.
using this performance test class:
Public Class Performance
Private _iterations As Integer
Private _displayDigits As Integer
Private _emptyTime As TimeSpan
Public Sub New(ByVal iterations As Integer, ByVal displayDigits As Integer)
_iterations = iterations
_displayDigits = displayDigits
_emptyTime = TimeSpan.Zero
_emptyTime = Take(Sub()
End Sub)
End Sub
Private Function Take(ByVal action As Action) As TimeSpan
Dim w As Stopwatch = Stopwatch.StartNew()
For i As Integer = 0 To _iterations - 1 Step 10
Action()
Action()
Action()
Action()
Action()
Action()
Action()
Action()
Action()
Action()
Next
w.Stop()
Return w.Elapsed - _emptyTime
End Function
Public Function Take(ByVal title As String, ByVal action As Action) As String
Dim Time As TimeSpan = Take(action)
Return title + " " + (Time.TotalMilliseconds / Convert.ToDouble(_iterations)).ToString("N" + _displayDigits.ToString()) + " ms."
End Function
End Class
You could also try using Redim Preserve. These statements are carry overs from the Visual Basic 6.0 days and are not considered the .NET way of doing things, but it is another option. There may be performance issues though according to this article.
Redim Preserve addressArray(addressArray.Length - 1)
Actually to delete the last item of array you would have to:
Redim Preserve addressArray(addressArray.Length - 2)
since they are zero based and the length is one based.
This will return all but the last "word/number" in a String as an array of Strings.
Return args.content.Split(" ").Take((args.content.Split(" ").Count - 1)).ToArray()
Related
So I've used visual basics (vb.net) for a bit now and understand some stuff. Right now I want to make a maths quiz that when I click a button it takes me to a new form and starts the quiz. When the quiz starts I want it so it gives the user random numbers and the user needs to answer it in a textbox and if correct it moves on to the next question (Basic, I should be able to do). IMPORTANT - my question is, there's a maths rule called BODMAS (Bracket.Order.Division.Multiply.Add.Subtract) and I want to add this rule into my coding instead of doing regular simple maths...
EXAMPLE question is 2 x (2+3) - 1 = ?
2 x 5 - 1 = ?
10 - 1 = ?
9 = 9
person writes answer to textbox and moves to next similar question
This is my first time using this but I wanted to write in-depth so people can understand. Please help me if you find a video explaining what I'm looking for or if someone has a file with a similar code I could download would be greatly appreciated!
Basically,you need to determine the range of numbers you use, and then match them randomly among '*', '/', '+', '-'. Then randomly insert brackets into it.
Private codeStr As String
Private Function GenerateMathsQuiz() As String
Dim r As Random = New Random()
Dim builder As StringBuilder = New StringBuilder()
'The maximum number of operations is five, and you can increase the number [5] to increase the difficulty
Dim numOfOperand As Integer = r.[Next](1, 5)
Dim numofBrackets As Integer = r.[Next](0, 2)
Dim randomNumber As Integer
For i As Integer = 0 To numOfOperand - 1
'All numbers will be random between 1 and 10
randomNumber = r.[Next](1, 10)
builder.Append(randomNumber)
Dim randomOperand As Integer = r.[Next](1, 4)
Dim operand As String = Nothing
Select Case randomOperand
Case 1
operand = "+"
Case 2
operand = "-"
Case 3
operand = "*"
Case 4
operand = "/"
End Select
builder.Append(operand)
Next
randomNumber = r.[Next](1, 10)
builder.Append(randomNumber)
If numofBrackets = 1 Then
codeStr = InsertBrackets(builder.ToString())
Else
codeStr = builder.ToString()
End If
Return codeStr
End Function
Public Function InsertBrackets(ByVal source As String) As String
Dim rx As Regex = New Regex("\d+", RegexOptions.Compiled Or RegexOptions.IgnoreCase)
Dim matches As MatchCollection = rx.Matches(source)
Dim count As Integer = matches.Count
Dim r As Random = New Random()
Dim numIndexFirst As Integer = r.[Next](0, count - 2)
Dim numIndexLast As Integer = r.[Next](1, count - 1)
While numIndexFirst >= numIndexLast
numIndexLast = r.[Next](1, count - 1)
End While
Dim result As String = source.Insert(matches(numIndexFirst).Index, "(")
result = result.Insert(matches(numIndexLast).Index + matches(numIndexLast).Length + 1, ")")
Return result
End Function
When you finish this, you will get a math quiz, then you need to know how to compile and run code at runtime.
Private Function GetResult(ByVal str As String) As String
Dim sb As StringBuilder = New StringBuilder("")
sb.Append("Namespace calculator" & vbCrLf)
sb.Append("Class calculate " & vbCrLf)
sb.Append("Public Function Main() As Integer " & vbCrLf)
sb.Append("Return " & str & vbCrLf)
sb.Append("End Function " & vbCrLf)
sb.Append("End Class " & vbCrLf)
sb.Append("End Namespace" & vbCrLf)
Dim CompilerParams As CompilerParameters = New CompilerParameters()
CompilerParams.GenerateInMemory = True
CompilerParams.TreatWarningsAsErrors = False
CompilerParams.GenerateExecutable = False
CompilerParams.CompilerOptions = "/optimize"
Dim references As String() = {"System.dll"}
CompilerParams.ReferencedAssemblies.AddRange(references)
Dim provider As VBCodeProvider = New VBCodeProvider()
Dim compile As CompilerResults = provider.CompileAssemblyFromSource(CompilerParams, sb.ToString())
If compile.Errors.HasErrors Then
Dim text As String = "Compile error: "
For Each ce As CompilerError In compile.Errors
text += "rn" & ce.ToString()
Next
Throw New Exception(text)
End If
Dim Instance = compile.CompiledAssembly.CreateInstance("calculator.calculate")
Dim type = Instance.GetType
Dim methodInfo = type.GetMethod("Main")
Return methodInfo.Invoke(Instance, Nothing).ToString()
End Function
Finally, you can use these methods like:
Private Sub GetMathQuizBtn_Click(sender As Object, e As EventArgs) Handles GetMathQuizBtn.Click
Label1.Text = GenerateMathsQuiz()
End Sub
Private Sub ResultBtn_Click(sender As Object, e As EventArgs) Handles ResultBtn.Click
If TextBox1.Text = GetResult(Label1.Text) Then
MessageBox.Show("bingo!")
TextBox1.Text = ""
Label1.Text = GenerateMathsQuiz()
Else
MessageBox.Show("result is wrong")
End If
End Sub
Result:
I got code for getting the first match. But the code does not get all matches. Can someone explain me how to do that? :)
Dim Start As Integer = 0, [End] As Integer = 0
If content.Contains(startString) AndAlso content.Contains(endString) Then
Start = content.IndexOf(startString, 0) + startString.Length
[End] = content.IndexOf(endString, Start)
Return content.Substring(Start, [End] - Start)
Else
Return String.Empty
End If
This works beautifuly for the first string and is easy to use. Just need to make it get a string array that i will use later (there are aprox. 5-10 strings that are always present between startString and endString).
Update:
Dim Searchstring As String
Searchstring = RichTextBox1.Text
Dim SearchStringPlus = Regex.Replace(Searchstring, "\s+", "+")
Dim SearchHTML As String
Dim WebClient1 As New Net.WebClient
SearchHTML = WebClient1.DownloadString("https://www.imdb.com/find?ref_=nv_sr_fn&q=" & SearchStringPlus & "&s=tt")
Dim SearchIndex As String = "<td class=""primary_photo""> <a href=""/title/tt"
Dim iSearch As System.IO.StreamWriter
iSearch = My.Computer.FileSystem.OpenTextFileWriter("iSearch.txt", False)
iSearch.WriteLine(SearchHTML)
iSearch.Close()
Dim SearchHTMLR As String
SearchHTMLR = IO.File.ReadAllLines("iSearch.txt").FirstOrDefault(Function(x) x.Contains(SearchIndex))
Dim titles As String
titles = GetStringBetween(SearchHTMLR, "<a href=""/title/", "/?ref_=fn_tt_tt_1")
MessageBox.Show(titles)
You can achieve this by using the Substring method.
Vb.Net
Private Function GetStringBetween(ByVal str As String, ByVal startStr As String, ByVal endStr As String) As String
Return str.Substring(startStr.Length, str.Length - (startStr.Length + endStr.Length))
End Function
C#
private string GetStringBetween(string str, string start, string end)
{
return str.Substring(start.Length, str.Length - (start.Length + end.Length));
}
My first question here, I'll try to be as clear as possible.
I have a text file that looks like this :
[...]
"tickets"
{
"436" "320000000400000083421a060100100104"
"674" "320000000400000083421a06010010010a"
"292" "320000000400000083421a0601001001f0"
"551" "320000000400000083421a0601001001da"
}
"99550"
{
"informations" "254"
"parameters" "-banana -lemon"
}
"99551"
{
"informations" "641"
"parameters" "-banana -lemon"
}
"550"
{
"informations" "551"
"parameters" "-banana -lemon"
}
"551"
{
"informations" "123"
"parameters" "-banana -lemon"
}
"552"
{
"informations" "987"
"parameters" "-banana -lemon"
}
[...]
What I want to do is:
search for this string in the text file :
"551"
{
add -apple to the parameters line which is 2 lines below, should look like this :
"parameters" "-banana -lemon -apple"
I think it's the only way to find this line, but I don't get the coding skills to get it done.
You can try something like this:
Function ReplaceSpecial(ByVal text As String, ByVal find As String, ByVal insert As String) As String
Dim allLines() As String = Split(text, vbCrLf)
Dim lineNumber = Array.IndexOf(allLines, find)
Dim lineToUpdate = Array.FindIndex(Of String)(allLines, lineNumber, Function(f) f.Trim.StartsWith("""parameters"""))
allLines(lineToUpdate) = allLines(lineToUpdate).Trim.Substring(0, allLines(lineToUpdate).Length - 1) & " " & insert & """"
Return Join(allLines, vbCrLf)
End Function
Sample Usage:
Assuming that your input text is in a textbox named InputTextBox the following code will show you updated text in OutputTextBox.
OutputTextBox.Text = ReplaceSpecial(InputTextBox.text, """550""", "-apple")
Here's another one, not much different than Pradeep Kumar's submission:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim FileName As String = "C:\Users\Mike\Documents\SomeFile.txt"
Dim lines As New List(Of String)(File.ReadAllLines(FileName))
AddParameterToSection(lines, "551", "-apple")
AddParameterToSection(lines, "552", "-orange")
File.WriteAllLines(FileName, lines)
End Sub
Private Sub AddParameterToSection(ByVal lines As List(Of String), ByVal sectionID As String, ByVal parameter As String)
Static DoubleQuote As String = Chr(34)
Static Parameters As String = DoubleQuote & "parameters" & DoubleQuote
Static PairOfDoubleQoutes As String = DoubleQuote & DoubleQuote
Dim header As String = DoubleQuote & sectionID & DoubleQuote
Dim index As Integer = lines.FindIndex(Function(x) x.Trim() = header)
If index <> -1 Then
Dim endBracket As Integer = lines.FindIndex(index, Function(x) x.Trim() = "}")
Dim paramIndex As Integer = lines.FindIndex(index, Function(x) x.Trim().StartsWith(Parameters))
If paramIndex <> -1 AndAlso paramIndex < endBracket Then
If lines(paramIndex).EndsWith(PairOfDoubleQoutes) Then
lines(paramIndex) = lines(paramIndex).Replace(PairOfDoubleQoutes, DoubleQuote & parameter & DoubleQuote)
Else
lines(paramIndex) = lines(paramIndex).TrimEnd(DoubleQuote) & " " & parameter & DoubleQuote
End If
End If
End If
End Sub
First off thanks for reading this, I've spent the last four hours trying to work this out.
Essentially I'm building a application in where the user inputs: date, Name, Phone number and instructor name to a simple csv .txt database file. I've got all that working.
Now all I need to do is somehow group the details together, and separate from other entries.
I now want to sort these grouped details by date through a bubble sort and then save it to another file. WHen I say sort, I want the other details to go along with the date.
The date when inputted to the application has to be: (yyMMddhhmm)
Eg: 1308290930 = 9:30 on 29/08/13
I can post what I've done thus far.
Public Class Form2
Dim currentRow As String()
Dim count As Integer
Dim one As Integer
Dim two As Integer
Dim three As Integer
Dim four As Integer
Dim catchit(100) As String
Dim count2 As Integer
Dim arrayone(50) As Integer
Dim arraytwo(50) As String
Dim arraythree(50) As Integer
Dim arrayfour(50) As String
Dim bigstring As String
Dim builder As Integer
Dim twodata As Integer
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Me.RichTextBox1.LoadFile("D:\completerecord.txt", RichTextBoxStreamType.PlainText)
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("D:\completerecord.txt")
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
Dim currentRow As String()
Dim count As Integer
count = 0
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
' makes one array to contain a record for each peice of text in the file
'MsgBox(currentField) '- test of Field Data
' builds a big string with new line-breaks for each line in the file
bigstring = bigstring & currentField + Environment.NewLine
'build two arrays for the two columns of data
If (count Mod 2 = 1) Then
arraytwo(two) = currentField
two = two + 1
'MsgBox(currentField)
ElseIf (count Mod 2 = 0) Then
arrayone(one) = currentField
one = one + 1
End If
count = count + 1
'MsgBox(count)
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Error Occured, Please contact Admin.")
End Try
End While
End Using
RichTextBox1.Text = bigstring
' MsgBox("test")
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim NoMoreSwaps As Boolean
Dim counter As Integer
Dim Temp As Integer
Dim Temp2 As String
Dim listcount As Integer
Dim builder As Integer
Dim bigString2 As String = ""
listcount = UBound(arraytwo)
'MsgBox(listcount)
builder = 0
'bigString2 = ""
counter = 0
Try
'this should sort the arrays using a Bubble Sort
Do Until NoMoreSwaps = True
NoMoreSwaps = True
For counter = 0 To (listcount - 1)
If arraytwo(counter) > arraytwo(counter + 1) Then
NoMoreSwaps = False
If arraytwo(counter + 1) > 0 Then
Temp = arraytwo(counter)
Temp2 = arrayone(counter)
arraytwo(counter) = arraytwo(counter + 1)
arrayone(counter) = arrayone(counter + 1)
arraytwo(counter + 1) = Temp
arrayone(counter + 1) = Temp2
End If
End If
Next
If listcount > -1 Then
listcount = listcount - 1
End If
Loop
'now we need to output arrays to the richtextbox first we will build a new string
'and we can save it to a new sorted file
Dim FILE_NAME As String = "D:\sorted.txt"
If System.IO.File.Exists(FILE_NAME) = True Then
Dim objWriter As New System.IO.StreamWriter(FILE_NAME, True)
While builder < listcount
bigString2 = bigString2 & arraytwo(builder) & "," & arrayone(builder) + Environment.NewLine
objWriter.Write(arraytwo(builder) & "," & arrayone(builder) + Environment.NewLine)
builder = builder + 1
End While
RichTextBox2.Text = bigString2
objWriter.Close()
MsgBox("Text written to log file")
Else
MsgBox("File Does Not Exist")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
Create a class to hold the information for each entry, like this:
Public Class MyEntry
Public Property TheDate() As DateTime
Get
Return m_Date
End Get
Set
m_Date = Value
End Set
End Property
Private m_Date As DateTime
Public Property Name() As String
Get
Return m_Name
End Get
Set
m_Name = Value
End Set
End Property
Private m_Name As String
Public Property PhoneNumber() As String
Get
Return m_PhoneNumber
End Get
Set
m_PhoneNumber = Value
End Set
End Property
Private m_PhoneNumber As String
Public Property Instructor() As String
Get
Return m_Instructor
End Get
Set
m_Instructor = Value
End Set
End Property
Private m_Instructor As String
Public Sub New(date As DateTime, name As String, phoneNumber As String, instructor As String)
TheDate = date
Name = name
PhoneNumber = phoneNumber
Instructor = instructor
End Sub
End Class
Now you can create a list of the above class, like this:
Private entries As var = New List(Of MyEntry) From { _
New MyEntry(DateTime.Now.AddDays(-1), "Dummy 1", "555-123-4567", "Instructor A"), _
New MyEntry(DateTime.Now.AddDays(-1), "Dummy 2", "555-124-4567", "Instructor B"), _
New MyEntry(DateTime.Now.AddDays(-1), "Dummy 3", "555-125-4567", "Instructor C"), _
New MyEntry(DateTime.Now.AddDays(-2), "Dummy 4", "555-126-4567", "Instructor A"), _
New MyEntry(DateTime.Now.AddDays(-2), "Dummy 5", "555-127-4567", "Instructor B") _
}
Note: You will need to substitute your real values here and would use some type of looping structure to do that.
Now you can apply the LINQ GroupBy function to the list of entries, like this:
Private entriesByDate As var = entries.GroupBy(Function(x) x.TheDate).ToList()
This results in a list of two entries for the dummy data I created above, your amount of groupings will vary based upon your actual data.
Now you could loop through the list of groups, like this:
For Each entry In entriesByDate
' Put logic here to save each group to file
Next
My suggestion is to add a marker at the end of reach recoord (date, time, etc.). I use "|". Then, when you read the data back, split the records into an array, and read them out using that.
So it would be:
130829|0930|<name>|<phone number>|etc
Do you understand?
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