Saving a list of words in visual basic - vb.net

How do I create a program that identifies the individual words in a sentence and store them in a list? I want to then get the program to create a list of positions for words in that list save these lists as a single file.
Module Module1
Sub Main()
Dim WordNumber As Integer = 0
Dim StartofWord As Integer = 1
Dim Text As String = ""
Dim L As Integer = 0
Dim Word As String
Console.WriteLine("Enter your sentence ")
Dim LotsofText As String = UCase(Console.ReadLine)
Console.WriteLine("Enter your word")
Word = UCase(Console.ReadLine())
If Mid(LotsofText, Len(LotsofText) - 1, 1) <> " " Then LotsofText = LotsofText + " "
For L = 1 To LotsofText.Length
If (Mid(LotsofText, L, 1)) = " " Then
WordNumber = WordNumber + 1
Text = (Mid(LotsofText, StartofWord, L - StartofWord))
'Console.WriteLine(Text)
StartofWord = L + 1
If Text = Word Then
Console.WriteLine(WordNumber)
End If
End If
Next
If Not Text = Word Then
Console.WriteLine("Error word not found")
End If
Console.Write("Press Enter to Exit")
Console.ReadLine()
End Sub
End Module

Split your sentence by blank " " , loop over all words and add the position to a list if the current word matches your search word.
Dim Sentence = "Hello from the other side and hello from hell"
Dim SearchWord = "Hello"
If Not String.IsNullOrWhiteSpace(Sentence) Then
SearchWord = SearchWord.Trim
Sentence = Sentence.Trim
Dim words = Sentence.Split(" ")
If Not words.Contains(SearchWord) Then Return
Dim searchWordPositions = New List(Of Integer)
For i = 0 To words.Length - 1
If words(i).Equals(SearchWord, StringComparison.InvariantCultureIgnoreCase) Then
searchWordPositions.Add(i)
End If
Next
Console.WriteLine(String.Concat("Found '", SearchWord, "' at Positions: ", String.Join(", ", searchWordPositions)))
End If
'Output:
Found 'Hello' at Positions: 0, 6
Instead of Console.WriteLine write it to a file.

Related

How do you replace the last occurance of a , with the word "and"?

How do you replace the last occurance of a , with the word and? Can you please give me an idea?
i have 3 checkboxes, 1 rich textbox
to display the output, 1 button
(Aparri) or (Camalanuigan) or (Lallo)
Cagayan(Aparri, Camalanuigan) or Cagayan(Aparri,Camalanuigan,Lallo)
I would like the output to be like this: #Cagayan(Aparri and Camalanuigan) or #Cagayan(Aparri,Camalanuigan And Lallo)
this is my code:
Dim rws As String
If Aparri.Checked = True Then
close_parenthesis.Checked = True
If rws = "" Then
rws = "(" + Aparri.Text
End If
End If
If Aparri.Checked = False Then
rws = ""
End If
If Camalanuigan.Checked = True Then
close_parenthesis.Checked = True
If rws = "" Then
rws = "(" + Camalanuigan.Text
Else
rws = rws & ", " & Camalanuigan.Text
End If
End If
If Lallo.Checked = True Then
close_parenthesis.Checked = True
If rws = "" Then
rws = "(" + Lallo.Text
Else
rws = rws & ", " & Lallo.Text
End If
End If
If close_parenthesis.Checked = True Then
If rws = "" Then
Else
rws = rws + close_parenthesis.Text
End If
End If
Display.Text = rws.ToString
Output: (Aparri,Camalanuigan,Lallo)
i want the out like this (Aparri,Camalanuigan and Lallo)
Here, I haven't even seen your code but I get what you want to do by looking at the picture. It can be done in shorter version but I have explained what's going on in each and every line so it's lengthy.
I have written this code:
'let's say the string is "Aparri, Camalanuigan, Lallo" . that's what your code does, right?
dim Strng as string = "Aparri, Camalanuigan, Lallo"
'now find the position of last appearing ","
Dim comaposition As Integer
comaposition = Strng.LastIndexOf(",") 'it is zero based
'if not found, it will return -1 and u can exit, no need to do the work
if commaposition = "-1" then
exit sub
end if
'remove the comma
Dim String_After_Removing_Comma As String
String_After_Removing_Comma = Strng.Remove(comaposition, 1)
'add "and" in the same position where comma was found
Dim final_string As String
final_string = String_After_Removing_Comma.Insert(comaposition, " and")
'show it on the textbox
DisplayTxt.Text = final_string
You can do this thing after finding your final string (rws in your code).
Hope this helps
You can use the following function to replace last occurrence.
Public Function ReplaceLastOccurrence(ByVal source As String, ByVal searchText As String, ByVal replace As String) As String
Dim position = source.LastIndexOf(searchText)
If (position = -1) Then Return source
Dim result = source.Remove(position, searchText.Length).Insert(position, replace)
Return result
End Function
and you use display text as
Display.Text = ReplaceLastOccurence(rws, ",", "and")
in your last line of code
You always can do it by yourself with single loop and knowledge about last index
' Create array of selected strings
Dim selectedTexts =
New List(Of CheckBox) From { Aparri, Camalanuigan, Lallo }.
Where(Function(checkbox) checkbox.Checked).
Select(Function(checkbox) checkbox.Text).
ToArray()
' Separate selected strings by delimeters
Dim lastIndex = selectedTexts.GetUpperBound(0)
Dim builder = New StringBuilder()
For i As Integer = 0 To lastIndex
If i > 0 Then
Dim delimeter = If(lastIndex > 0 AndAlso lastIndex = i, " and ", ", ")
builder.Append(delimeter)
End If
builder.Append(test(i))
Next
' Wrap with parenthesis if result not empty
If builder.Length > 0 Then
builder.Insert(0, "(")
Dim close = If(close_parenthesis.Checked, close_parenthesis.Text, "")
builder.Append(close)
End If
' Print result
Display.Text = builder.ToString()

Splitting a full name string to separate variables (first, middle and last) without using the split function

So I was given the task to bifurcate a string with a full name and then print out the first and last name separately. For instance, input: Steve Robertson, output: First name: Steve Last name: Robertson.
I succeeded, it was fairly easy. But I'm having having trouble in dividing a full name string to first, last and middle. Here's what I've done so far.
Sub Main()
Dim string1 As String = ""
Dim string2 As String = ""
Dim string3 As String = ""
Dim string4 As String = ""
Dim temp1 As String = ""
Dim integer1 As Integer = 1
Console.WriteLine("Enter the string you want to bifurcate: ")
string1 = Console.ReadLine()
While integer1 <> 0
integer1 = InStr(string1, " ")
Console.WriteLine(string1)
string2 = Left(string1, integer1)
Console.WriteLine(string2)
string3 = Mid(string1, integer1 + 1)
Console.WriteLine(string3)
string4 = Mid(string1, integer1 + 1)
Console.WriteLine(string4)
string1 = string4
End While
Console.WriteLine("First name is: " & string2)
Console.WriteLine("Second name is: " & string3)
Console.WriteLine("Third name is: " & string4)
Console.ReadKey()
End Sub
Keep in mind that I'm only printing almost every single variable to see what their value is during the iteration. I can only use the len() function and whatever is already in the code.
EDIT:
So I fiddled around and finally got the thing, without the loop, but I was wondering if there was a cleaner/right way to do this without repeating the variables and also not needing to create any new ones either.
Sub Main()
Dim string1 As String = ""
Dim string2 As String = ""
Dim string3 As String = ""
Dim string4 As String = ""
Dim integer1 As Integer
Console.WriteLine("Enter the string you want to split: ")
string1 = Console.ReadLine()
integer1 = InStr(string1, " ")
string2 = Left(string1, integer1)
string3 = Mid(string1, integer1 + 1)
integer1 = InStr(string3, " ")
string4 = Left(string3, integer1)
string3 = Mid(string3, integer1 + 1)
Console.WriteLine("The first name is: " & string2)
Console.WriteLine("The middle name is: " & string4)
Console.WriteLine("The last name is: " & string3)
Console.ReadKey()
End Sub
Here is one way to do it. Loop through the characters from the input of the user. Continue to do so concatenating them together and throw them into a List(Of String) that way the can be easily written out at the end... This account's for multiple spaces as well if there's more than one in between names. Also I put some comment's into the code so it can be easier to understand.
Note: This is only one way to do it... (there are other ways)
CODE TRIED AND TESTED
Dim nList As New List(Of String)
Dim uStr As String = String.Empty
Console.WriteLine("Enter the string you want to bifurcate: ")
uStr = Console.ReadLine()
If Not String.IsNullOrEmpty(uStr) Then 'Make sure something was entered...
Dim tStr As String = String.Empty
'Loop through user's input...
Do Until uStr = String.Empty
For Each c As Char In uStr
If Not Char.IsWhiteSpace(c) Then 'If it's a space we can add to the current string...
tStr &= c.ToString
Else
'We can assume its another section of the name...
Exit For
End If
Next
'If its a space, remove it from current string...
If String.IsNullOrEmpty(tStr) Then uStr = uStr.Remove(0, tStr.Length + 1) : Continue Do
'Add the string to the list, could be first name, middle or lastname?
If nList.Count = 0 Then
nList.Add("First Name: " & tStr)
ElseIf nList.Count = 1 Then
nList.Add("Middle Name: " & tStr)
ElseIf nList.Count = 2 Then
nList.Add("Last Name: " & tStr)
End If
'Now we can remove what we got from the users input...
uStr = uStr.Remove(0, tStr.Length)
tStr = String.Empty
Loop
End If
'Finally write out the values...
Console.WriteLine(String.Join(Environment.NewLine, nList.ToArray))
Console.ReadLine()
Screenshot Of Program
Maybe something like this
Dim fullName = "Juan Perez"
Dim name = fullName.Substring(0, fullName.IndexOf(" "))
Dim lastName = fullName.Substring(fullName.IndexOf(" ") + 1)
How to separate full name string
I would suggest that you design extension methods that will return First and Last Name
Module Module1
<Extension()>
Public Function returnFirst(ByVal fullName As String) As String
Return fullName.Substring(0, fullName.IndexOf(" "))
End Function
<Extension()>
Public Function returnLast(ByVal fullName As String) As String
Return fullName.Substring(fullName.IndexOf(" ") + 1)
End Function
End Module
'call it
'import module1
Dim Name as string = 'FirstName LastName'
MessageBox.Show(NAME.returnFirst)
MessageBox.Show(NAME.returnLast)

Compare two strings and find where letter positions match

I want to do a bitwise and on two strings so that:
Given:
Dim word As String = "abcd"
Dim temp As String = "a-d-"
I want to return only the 'a'
Given:
Dim word As String = "abcd"
Dim temp As String = "a--d"
I want to return only the 'a--d'
I have tried intersect, but it only finds characters in one string that match the characters in the other regardless of position.
I've used the '-' to represent spaces here.
Any suggestions would be appreciated.
This will handle strings with mis-matched lengths:
Public Function CheckMask(ByVal word As String, ByVal mask As String) As String
Dim wordChars() As Char = word.ToCharArray()
Dim maskChars() As Char = mask.ToCharArray()
Dim i As Integer = 0
While i < wordChars.Length AndAlso i < maskChars.Length
If wordChars(i) <> maskChars(i) Then wordChars(i) = " "c
i = i + 1
End While
'If string lengths are equal or the mask is longer, we're done
'If the word is longer, need to set remaining characters to " "
While i < wordChars.Length
wordChars(i) = " "c
End While
Return New String(wordChars)
End Function
Dim Res As String = ""
For i = 0 To Math.Min(StrA.Length, StrB.Length) - 1
If StrA(i) = StrB(i) Then Res &= StrA(i) Else Res &= " "
Next
Return Res
This basically loops to the end of the shorter one of the two strings. If the letters at a given position match the letter is added to the result, else a space is added.
Dim sFirstWord As String = "qwerty"
Dim sSecndWord As String = "qseftg"
Dim sResult As String = ""
For i As Integer = 0 To Math.Min(sFirstWord.Length, sSecndWord.Length) - 1
If sFirstWord(i) = sSecndWord(i) Then
sResult &= sFirstWord(i)
Else
sResult &= " "
End If
Next
sResult will hold: "q e t "

VB.net get the first word after a specified string

I need to get the first word only, after a specified string like so (pseudo):
my_string = "Hello Mr. John, how are you today?"
my_search_string = "are"
result = "you"
I tried to do it by using the following approach but i get the rest of the string after my "key" string and not a single word.
Dim search_string As String = "key"
Dim x As Integer = InStr(Textbox1.text, search_string)
Dim word_after_key As String = Textbox1.text.Substring(x + search_string.Length - 1)
Try this:
Dim str = "Hello Mr. John, how are you today?"
Dim key = " are "
Dim i = str.IndexOf(key)
If i <> -1 Then
i += key.Length
Dim j = str.IndexOf(" ", i)
If j <> -1 Then
Dim result = str.Substring(i, j - i)
End If
End If
Or this perhaps:
Dim str = "Hello Mr. John, how are you today?"
Dim key = "are"
Dim words = str.Split(" "C)
Dim i = Array.IndexOf(words, key)
If i <> -1 AndAlso i <> words.Length - 1 Then
Dim result = words(i + 1)
End If
This works too.
Dim my_string as String = "Hello Mr. John, how are you today?"
Dim SearchString As String = "are"
Dim StartP As Integer = InStr(my_string, SearchString) + Len(SearchString) + 1
' to account for the space
If StartP > 0 Then
Dim EndP As Integer = InStr(StartP, my_string, " ")
MsgBox(Mid(my_string, StartP, EndP - StartP))
End If
Dim sa As String
Dim s As String
Dim sp() As String
sa = TextBox1.Text 'this text box contains value **Open Ended Schemes(Debt Scheme - Banking and PSU Fund)**
sp = sa.Split("(") 'Here u get the output as **Debt Scheme - Banking and PSU Fund)** which means content after the open bracket...
sp = sp(1).Split(")") 'Here u get the output as Debt Scheme - Banking and PSU Fund which means content till the close bracket...
s = Split(sp(0))(0) 'Here it will take the first word, which means u will get the output as **Debt**
s = Split(sp(0))(1) 'Change the index as per the word u want, here u get the output as **Scheme**

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