Finding the position of a specified string in another string - vb.net

I need to find the position of a changing specified word in a string, and I need it to be very specific so it doesn't include words without spaces so say if I was looking for the word 'Hi' It would only return true if it was checking 'Hi' and not 'HiExample'.
Code:
Dim userString As String = userInput.Text
userString = userString.ToLower()
Dim d As New Dictionary(Of String, Integer)
Dim wordString = userString.ToLower().Split(" "c)
Dim iList As New List(Of String)()
For Each word In wordString
If d.ContainsKey(word) Then
d(word) += 1
iList.Add(word)
Else
d.Add(word, 1)
End If
Next
For Each de In d
For i As Integer = 0 To wordString.Count - 1
Dim index As Integer = userString.IndexOf(de.Key)
output.Text &= "Word: " & de.Key & " Occurrence: " & de.Value & " Position: " & GET POSTION OF EACH WORD HERE & Environment.NewLine
Next
Next
Checking for upper case or lower case will not be necessary as I have already converted the string into lower case.
Thanks,
Matt

you can try Regex
For Each de In d
Dim index As Integer = Regex.Matches(userString, "(?<=^|\b|\s)" & Regex.Escape(de.Key) & "(?=\s|\b|$)")(0).Index
Console.WriteLine("Word: " & de.Key & " Occurrence: " & de.Value & " Position: " & index)
Next
this might get you started

Related

Split text in all lines inside of a string

Originally the Keywords will we pulled out from a text file located on a web server.
Dim KeyWords As String = Split(Split(TempSMTPFile, "# Keywords #")(1), "# Keywords #")(0)
I want to create a function that will split out all the keywords inside a string
The keywords in this example will be:
' This list might be changed to more or less keywords.
Dim KeyWords As String = "[One=Test1]" & vbNewLine & "[Two=Test2]" & vbNewLine & "[Three=Test3]"
' I Need a function to split out all keywords and do below check between all splits.
If KeyWords.ToLower.Contains("[" & Splited_keyword & "=") Then ' One, Two, Three
MsgBox(Split(Split(KeyWords, "[" & Splited_keyword & "=")(1), "]")(0)) ' Test1, Test2, Test3
End If
' This should print OneTest1, TwoTest2, ThreeTest3
Thanks for your comments, I was able to solve this with this solution.
Dim str As String() = keywords.Split(New [Char]() {CChar(vbCrLf)})
For Each s As String In str
If s.Contains("[") Then
Dim SplittedKeyword = Split(Split(s, "[")(1), "=")(0)
If TextUserShortDescription.Text.ToLower.Contains(SplittedKeyword.ToLower) Then
MsgBox(SplittedKeyword & (Split(Split(s, "[" & SplittedKeyword & "=")(1), "]")(0)))
End If
End If
Next
This could help you (untested):
Dim keyValues as String()
keyValues = KeyWords.Split(Environment.NewLine)
For Each (keyvalue as string in keyValues)
MsgBox(keyvalue.SubString(1, keyvalue.IndexOf("["c) + " " + keyvalue.SubString(keyvalue.IndexOf("="c), keyvalue.LastIndexOf("]"c)
End For

extracting text from comma separated values in visual basic

I have such kind of data in a text file:
12343,M,Helen Beyer,92149999,21,F,10,F,F,T,T,T,F,F
54326,F,Donna Noble,92148888,19,M,99,T,F,T,F,T,F,T
99999,M,Ed Harrison,92147777,28,F,5,F,F,F,F,F,F,T
88886,F,Amy Pond,92146666,31,M,2,T,F,T,T,T,T,T
37378,F,Martha Jones,92144444,30,M,5,T,F,F,F,T,T,T
22444,M,Tom Scully,92145555,42,F,6,T,T,T,T,T,T,T
81184,F,Sarah Jane Smith,92143333,22,F,5,F,F,F,T,T,T,F
97539,M,Angus Harley,92142222,22,M,9,F,T,F,T,T,T,T
24686,F,Rose Tyler,92142222,22,M,5,F,F,F,T,T,T,F
11113,F,Jo Grant,92142222,22,M,5,F,F,F,T,T,T,F
I want to extract the Initial of the first name and complete surname. So the output should look like:
H. Beyer, M
D. Noble, F
E. Harrison, M
The problem is that I should not use String Split function. Instead I have to do it using any other way of string handling.
This is my code:
Public Sub btn_IniSurGen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_IniSurGen.Click
Dim vFileName As String = "C:\temp\members.txt"
Dim vText As String = String.Empty
If Not File.Exists(vFileName) Then
lbl_Output.Text = "The file " & vFileName & " does not exist"
Else
Dim rvSR As New IO.StreamReader(vFileName)
Do While rvSR.Peek <> -1
vText = rvSR.ReadLine() & vbNewLine
lbl_Output.Text += vText.Substring(8, 1)
Loop
rvSR.Close()
End If
End Sub
You can use the TextFieldParserClass. It will parse the file and return the results directly to you as a string array.
Using MyReader As New Microsoft.VisualBasic.FileIO.
TextFieldParser("c:\logs\bigfile")
MyReader.TextFieldType =
Microsoft.VisualBasic.FileIO.FieldType.Delimited
MyReader.Delimiters = New String() {","}
Dim currentRow As String()
'Loop through all of the fields in the file.
'If any lines are corrupt, report an error and continue parsing.
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
' Include code here to handle the row.
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message &
" is invalid. Skipping")
End Try
End While
End Using
For your wanted result, you may changed
lbl_Output.Text += vText.Substring(8, 1)
to
'declare this first
Dim sInit as String
Dim sName as String
sInit = vText.Substring(6, 1)
sName = ""
For x as Integer = 8 to vText.Length - 1
if vText.Substring(x) = "," Then Exit For
sName &= vText.Substring(x)
Next
lbl_Output.Text += sName & ", " & sInit
But better you have more than one lbl_Output ...
Something like this should work:
Dim lines As New List(Of String)
For Each s As String In File.ReadAllLines("textfile3.txt")
Dim temp As String = ""
s = s.Substring(s.IndexOf(","c) + 1)
temp = ", " + s.First
s = s.Substring(s.IndexOf(","c) + 1)
temp = s.First + ". " + s.Substring(s.IndexOf(" "c), s.IndexOf(","c) - s.IndexOf(" "c)) + temp
lines.Add(temp)
Next
The list Lines will contain the strings you need.

Email a table using VB.Net

I need to send an email with a table that has variable values in each cell. I can do this using any method (html via email, an excel/word table, etc.). The only hitch is due to the restrictions of the Emailer program and System.Net.Mail import, it has to be a string.
Here's what I have so far:
Imports DelayEmailer.DelayTrackerWs
Imports System.Configuration
Public Class DelayEmailer
Public Shared Sub Main()
Dim ws As New DelayTrackerWs.DelayUploader
Dim delays As DelayTrackerWs.Delay()
Dim emailer As New Emailer()
Dim delaystring As String
delays = ws.SearchDelaysDate(DelayTrackerWs.AreaEnum.QT, DelayTrackerWs.UnitEnum.QT, Now.AddDays(-1), Now)
delaystring = "Delays" & vbNewLine
delaystring &= "Facilty Start Time Status Category Reason Comment"
For i = 0 To delays.Length - 1
delaystring &= vbNewLine & delays(i).Facility & " "
delaystring &= FormatDateTime(delays(i).DelayStartDateTime, DateFormat.ShortDate) & " "
delaystring &= FormatDateTime(delays(i).DelayStartDateTime, DateFormat.ShortTime) & " "
'delaystring &= delays(i).DelayDuration & " "
delaystring &= delays(i).Status & " "
delaystring &= delays(i).CategoryCode & " "
delaystring &= delays(i).ReasonCode & " "
delaystring &= delays(i).Comment
Next
emailer.Send(ConfigurationManager.AppSettings("EmailList"), "delays", delaystring)
End Sub
As you can see, I currently have just a bunch of concatenated strings that line up if the values of each delays(i) are the same. The other problem is that this needs to be easily viewable via mobile devices and with the strings, it wraps and gets really unreadable. A table here should fix this.
You can send html email from .NET using MailMessage and SmtpClient classes, create an email template as string and set MailMessage's IsBodyHtml property to true:
Dim strHeader As String = "<table><tbody>"
Dim strFooter As String = "</tbody></table>"
Dim sbContent As New StringBuilder()
For i As Integer = 1 To rows
sbContent.Append("<tr>")
For j As Integer = 1 To cols
sbContent.Append(String.Format("<td>{0}</td>", YOUR_TD_VALUE_STRING))
Next j
sbContent.Append("</tr>");
Next i
Dim emailTemplate As String = strHeader & sbContent.ToString() & strFooter
...

Get Text between characters in a string

I have a text file with a list of music that looks like this:
BeginSong{
Song Name
Artist
Genre
}EndSong
There are multiple instances of this.
I'm wanting to get the text between the BeginSong{ and }EndSong and put the song info
into a string array. Then I want to add each instance to a ListBox as Artist - Song Name
(that part I'm sure I can figure out though). I hope that was a clear description.
Use the ReadLine() function of the FileStream
since you already know the order of the information, you should be able to loop all File Lines and store them in their corresponding properties.
Pseudo:
WHILE Reader.Read()
Store Line in BeginSongTextVariable
Read Next Line
Store Line in SongNameVariable
Read Next Line
Store Line in ArtistNameVariable
Read Next Line
Store Line in GenreVariable
Read Next Line
Store Line in EndSongTextVariable
Add The Above Variables in List
End While
You can use a regular expression with named groups:
BeginSong{\n(?<song_name>.*)\n(?<artist>.*)\n(?<genre>.*)\n}EndSong
Something like this:
Imports System.Text.RegularExpressions
'...
Dim s As New Regex("BeginSong{\n(?<song_name>.*)\n(?<artist>.*)\n(?<genre>.*)\n}EndSong")
Dim mc As MatchCollection = s.Matches(inputFile)
For Each m As Match In mc
Dim song_name As String = m.Groups("song_name").Value
Dim artist As String = m.Groups("artist").Value
Dim genre As String = m.Groups("genre").Value
'use or store these values as planned
Next
There is a nice answer from Neolisk that uses Regular Expressions. But since you also included the VB6 tag in addition to VB.NET, I'll take a shot at a VB6 solution.
You can use the string Split function, and split on the "ends", i.e. "BeginSong{" and "}EndSong"
Dim songInfos As String
Dim firstArray() As String
Dim secondArray() As String
Dim thirdArray() As String
Dim songInfoArray() As String
Dim i As Integer
Dim songCounter As Integer
' to test:
songInfos = songInfos & "BeginSong{" & vbNewLine
songInfos = songInfos & "Song Name1" & vbNewLine
songInfos = songInfos & "Artist1" & vbNewLine
songInfos = songInfos & "Genre1" & vbNewLine
songInfos = songInfos & "}EndSong" & vbNewLine
songInfos = songInfos & "BeginSong{" & vbNewLine
songInfos = songInfos & "Song Name2" & vbNewLine
songInfos = songInfos & "Artist2" & vbNewLine
songInfos = songInfos & "Genre2" & vbNewLine
songInfos = songInfos & "}EndSong"
firstArray = Split(songInfos, "BeginSong{")
songCounter = 0
ReDim songInfoArray(2, 0)
For i = 1 To UBound(firstArray) Step 1
secondArray = Split(firstArray(i), "}EndSong")
thirdArray = Split(secondArray(0), vbNewLine)
songInfoArray(0, songCounter) = thirdArray(1)
songInfoArray(1, songCounter) = thirdArray(2)
songInfoArray(2, songCounter) = thirdArray(3)
songCounter = songCounter + 1
If i < UBound(firstArray) Then
ReDim Preserve songInfoArray(2, songCounter)
End If
Next i
The watch after the last line. Note the structure of songInfoArray, which was required for it to be ReDimmed

Filter Data from dataset that is passed to textbox

I am iterating through columns in a datagridview in vb net and passing the
values to a textbox. I need to be able to filter out the emails which are in Cell(4), so that there are no duplicate emails for any single customer.
I have no idea of how to do this using a dataset.
EmailTableAdapter.Fill(Me.EmailDataset.Email)
Dim r As String = String.Empty
For i As Integer = 0 To Me.EmailDataGridView.RowCount - 1
r = r & EmailDataGridView.Rows(i).Cells(7).Value.ToString & " - " & EmailDataGridView.Rows(i).Cells(4).Value.ToString & vbNewLine
Next
TextBox2.Text = (r)
One way to filter out rows with duplicate values in Cells(4) would be to iterate through the grid rows, stuffing items into a Dictionary using Cells(4) values as the Key, and then iterate through the Dictionary to build your "r" string. Such a solution would look something like this:
EmailTableAdapter.Fill(Me.EmailDataset.Email)
Dim EmailDict As New Dictionary(Of String, String)
For i As Integer = 0 To Me.EmailDataGridView.RowCount - 1
If Not EmailDict.ContainsKey(EmailDataGridView.Rows(i).Cells(4).Value.ToString) Then
EmailDict.Add(EmailDataGridView.Rows(i).Cells(4).Value.ToString, EmailDataGridView.Rows(i).Cells(7).Value.ToString)
End If
Next
Dim EmailPair As KeyValuePair(Of String, String)
Dim r As String = String.Empty
For Each EmailPair In EmailDict
r &= EmailPair.Value & " - " & EmailPair.Key & vbNewLine
Next
TextBox2.Text = (r)