Find and replace using Listbox Vb.net

℡╲_俬逩灬. 提交于 2019-12-12 18:11:53

问题


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)


来源:https://stackoverflow.com/questions/7430168/find-and-replace-using-listbox-vb-net

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!