Find and replace using Listbox Vb.net

2019-07-20 08:43发布

问题:

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

回答1:

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)