Find and replace using Listbox Vb.net - vb.net

ok have a list of 84000 words , and have some articles in these articles i want to replace first occurrence of each word i have in listbox e.g
For Each item In ListBox1.Items
Dim mytext As String = "My some text this text is very long text and i want to replace this"
If ListBox1.Items.Contains(mytext) Then
mytext = Replace(mytext, mytext, "String to replace",Count:=1)
End If
Next
but it used to replace the whole mytext i want to replace words in mytext and also it hang the system and very very slow and help or idea please

It looks like you want to replace everything with the same string, but the code below is easily adaptable to other cases but I go with it for now.
To simplify I am assuming that you want to replace words and the words are only seperated by spaces (' ').
First make a dictionary out of the Items in the listbox:
dim dict = ListBox1.Items.Cast(of object).ToDictionary(function(x) x.ToString())
Then get yourself all words:
dim words = mytext.Split(New [Char](){" "c});
and a word-transform:
dim replaceWith = "your replacement";
dim mapWords as Func(of string,string) = _
function(word) IIf(dict.ContainsKey(word), replaceWith, word)
then transform the words and concatenate them again with ' ':
dim result = String.Join(" ", words.Select(function(word) mapWords(word)))
and you should be done.
If you want to replace with separate words just make the dictionaries values your replacement and switch the mapWords-function with
dim mapWords as Func(of string,string) = _
function(word) IIf(dict.ContainsKey(word), dict(word), word)

Related

Displaying each element of array on new line

Please consider I am very new with VB.NET when attempting to read and answer my question
I have a textbox that takes in a list of words separated with a comma on the same line. When button is clicked string gets assigned to variable text and I then split it to variable arrayText.
Then I loop over it and display each element of array on new line.
My code looks as follows
Dim text As String
Dim arrayText() As String
text = TextBox1.Text
arrayText = text.Split(",") 'every "," generates new array index, removes ","
text = ""
For i = 0 To arrayText.Length Step 1
text = arrayText(i) & vbCrLf
MsgBox(text)
Next
When debugging I get error message array out of bounds, however when I remove the newline character (vbCrLf) it displays my text, word for word in a messagebox (which I am using for debugging) and at the end of the loop it kicks out with same error message.
What am I doing wrong here, any improvement suggestions?
Though walther answer is right, i suggest you to use a List(Of String) and a For Each...Next loop.
A list is more "modern" and most of the times it is preferred over an array in vb.net. You can use Environment.NewLine instead of vbCrLf. I'm not sure what exactly you want to do, but I dont think that using a MsgBox is the optimal way to present the seperated words. Here is a simple example of what I think you should do :
' Hold the text from the text box.
Dim FullText As String = TextBox1.Text
Dim SeperatedWords As New List(Of String)
' ToList function converts the array to a list.
SeperatedWords = FullText.Split(",").ToList
' Reset the text for re-presentation.
FullText = ""
' Goes through all the seperated words and assign them to FullText with a new line.
For Each Word As String In SeperatedWords
FullText = FullText & Word & Environment.NewLine
Next
' Present the new list in the text box.
TextBox1.Text = FullText
For i = 0 To arrayText.Length - 1 Step 1
Last element has index of length of array - 1.

Lowercase the first word

Does anybody know how to lowercase the first word for each line in a textbox?
Not the first letter, the first word.
I tried like this but it doesn't work:
For Each iz As String In txtCode.Text.Substring(0, txtCode.Text.IndexOf(" "))
iz = LCase(iz)
Next
When you call Substring, it is making a copy of that portion of the string and returning it as a new string object. So, even if you were successfully changing the value of that returned sub-string, it still would not change the original string in the Text property.
However, strings in .NET are immutable reference-types, so when you set iz = ... all you are doing is re-assigning the iz variable to point to yet another new string object. When you set iz, you aren't even touching the value of that copied sub-string to which it previously pointed.
In order to change the value of the text box, you must actually assign a new string value to its Text property, like this:
txtCode.Text = "the new value"
Since that is the case, I would recommend building a new string, using a StringBuilder object, and then, once the modified string is complete, then set the text box's Text property to that new string, for instance:
Dim builder As New StringBuilder()
For Each line As String In txtCode.Text.Split({Environment.NewLine}, StringSplitOptions.None)
' Fix case and append line to builder
Next
txtCode.Text = builder.ToString()
The solutions here are interesting but they are ignoring a fundamental tool of .NET: regular expressions. The solution can be written in one expression:
Dim result = Regex.Replace(txtCode.Text, "^\w+",
Function (match) match.Value.ToLower(), RegexOptions.Multiline)
(This requires the import System.Text.RegularExpressions.)
This solution is likely more efficient than all the other solutions here (It’s definitely more efficient than most), and it’s less code, thus less chance of a bug and easier to understand and to maintain.
The problem with your code is that you are running the loop only on each character of the first word in the whole TextBox text.
This code is looping over each line and takes the first word:
For Each line As String In txtCode.Text.Split(Environment.NewLine)
line = line.Trim().ToLower()
If line.IndexOf(" ") > 0 Then
line = line.Substring(0, line.IndexOf(" ")).Trim()
End If
// do something with 'line' here
Next
Loop through each of the lines of the textbox, splitting all of the words in the line, making sure to .ToLower() the first word:
Dim strResults As String = String.Empty
For Each strLine As String In IO.File.ReadAllText("C:\Test\StackFlow.txt").Split(ControlChars.NewLine)
Dim lstWords As List(Of String) = strLine.Split(" ").ToList()
If Not lstWords Is Nothing Then
strResults += lstWords(0).ToLower()
If lstWords.Count > 1 Then
For intCursor As Integer = 1 To (lstWords.Count - 1)
strResults += " " & lstWords(intCursor)
Next
End If
End If
Next
I used your ideas guys and i made it up to it like this:
For Each line As String In txtCode.Text.Split(Environment.NewLine)
Dim abc() As String = line.Split(" ")
txtCode.Text = txtCode.Text.Replace(abc(0), LCase(abc(0)))
Next
It works like this. Thank you all.

Find position in array of strings in Word VBA

I have an array of strings "alpha", "beta"... and I'd like to test another string string2 against this to return 1, if string2 = "alpha", 2 if it equals "beta" etc.
I could do this if it were Excel using application.match, but this doesn't exist in Word.
The end goal is to return the unicode value for the appropriate Greek letter from the name of the letter, so if there's a better way of doing it, I'm open to suggestions. Maybe I've been writing too much python, and lists seem like the easy way.
You need to loop through the array and test each value against the searched value.
Here's some pseudo code to get you started.
Dim greek() As String
Dim x As Integer
Dim searchString As String
Dim match As Integer
For x = LBound(greek) To UBound(greek)
If greek(x) = searchString Then
match = x
Exit For
End If
Next x

How to remove letters?

i just wanna ask:
i have a label40.text
with a content of {a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}
and i also have have a label39.text that will change its output everytime a certain changes happens.
My question is
How can i embed this simulation through a code?
If Label39.text = "a" then the content of label40.text "a" will be remove and the list of alphabets will be remain alphabetically.
I want that also to be happen anytime my label39.text will change its value "RANDOMLY"
Example if label39.text = "a,b,c,d,x,z" then
label40.text = "e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y"
this is my code so far
Dim patterns As String
patterns = Label39.Text
Dim tobefollow As String
tobefollow = Label40.Text
Dim matches As MatchCollection = Regex.Matches(patterns, tobefollow)
If Regex.IsMatch(patterns, tobefollow) Then
'this where i will put my code to make my example
End If
First of all, note that you are populating the patterns and tobefollow variables wrongly (you were doing it right in the other question); it should be:
patterns = Label40.Text
tobefollow = Label39.Text
Also bear in mind that what you want can easily be accomplished without relying on Regex; for example via:
If (Label40.Text.ToLower().Contains(Label39.Text.ToLower())) Then
'this where i will put my code to make my example
End If
Regarding what you want this time, you can rely on .Replace: .Replace("text to be deleted", "") will remove this letter; but you have also to account for the commas. Code to be put inside the condition:
Dim origString As String = Label40.Text
Label40.Text = Label40.Text.ToLower().Replace(Label39.Text.ToLower() & ",", "")
If (origString = Label40.Text) Then
'It means that it does not have any comma, that is, refers to the last letter
Label40.Text = Label40.Text.ToLower().Replace("," & Label39.Text.ToLower(), "")
End If
An alternate answer would to use the String.Split and the String.Join Methods to breakdown your strings into individual characters then remove them from the List and join them back together. Here is a Function that does that:
Private Function RemoveLetters(str1 As String, str2 As String) As String
Dim sep() As String = {","}
Dim list1 As List(Of String) = str1.Split(sep, StringSplitOptions.None).ToList
Dim list2 As List(Of String) = str2.Split(sep, StringSplitOptions.None).ToList
For Each s As String In list2
list1.Remove(s)
Next
Return String.Join(",", list1)
End Function
you would use it like this:
Label40.Text = RemoveLetters(Label40.Text, Label39.Text)

Read text file with tab and carraige return format to store them in array

I have to text file in the following format :
Word[tab][tab]Word[Carriage Return]
Word[tab][tab]Word[Carriage Return]
Word[tab][tab]Word[Carriage Return]
I want to get all the words before the tab into one array or to create a new text file and the all the words after the tab into another array or create a new text file too.
Here my function to get the words before tab into an array :
Protected Sub MakeWordListBeforeTab()
Dim filename As String = "D:\lao\00001.txt"
'read from file'
Dim MyStream As New StreamReader(filename)
'words before tab
Dim WordBeforeTabArr() As String = MyStream.ReadToEnd.Split(CChar("\t"))
MyStream.Close()
'test to see the word in array
For d As Integer = 0 To WordBeforeTabArr.Length - 1
MsgBox(WordBeforeTabArr(d))
Next
End Sub
I wrote the above function to get all words before tab but I got all the words into array. I've been trying to use the Split method above. What is another method to split those words ? Can anyone show me some code to get this done right ?
I know this can be done with regular expression but I don't know regex yet. If you can show me how to get this done with regex it'll be awesome. Thanks.
You could try the split function on String. It could be used like this:
Dim lines() As String = IO.File.ReadAllLines(filename)
For Each line As String In lines
Dim words() As String = _
line.Split(New Char() {vbTab}, StringSplitOptions.RemoveEmptyEntries)
Next
The words array for each line would the two words. One word at each position. You could fill your two arrays or write the values out to a text file or file as you split the lines of the input file in the loop.
First of all above code is not compiling: See proper code as follows:
Dim lines() As String = IO.File.ReadAllLines(test_Filename)
For Each line As String In lines
Dim words() As String = _
line.Split("\t".ToCharArray()(0), StringSplitOptions.RemoveEmptyEntries)
Next