简体   繁体   English

用替换字符串中的相同单词替换字符串

[英]Replace string with same word in replacement string occurring

I have a textbox and if I type "Dog", My application is supposed to replace "Dog" with "Cute Dog". 我有一个textbox ,如果我键入“狗”,我的应用程序应该用“可爱的狗”取代“狗”。 But when I try and run it, lots of text is generated because it is finds "Dog" in "cute dog" that it has just replaced. 但是当我尝试运行它时,会生成大量文本,因为它在“可爱的狗”中找到它刚刚替换的“狗”。 Here is the code: 这是代码:

txtMain.Text = Microsoft.VisualBasic.Strings.Replace(txtMain.Text, "Dog", "Cute Dog", 1, -1, Constants.vbTextCompare)
            txtMain.Select(txtMain.Text.Length, 0)

this is being triggered on the text changed event. 这是在text changed事件上触发的。

The reason is that replacing the text like that fires the TextChanged-event again because that ... well ... changes the text of the TextBox. 原因是替换像这样的文本会再次触发TextChanged事件,因为......好吧......更改了TextBox的文本。 It's not an UI-only event if users change anything on their screen. 如果用户在屏幕上更改任何内容,则不是仅限UI的事件。

Now thats what makes your application write "cute cute dog" then, and with that fires the event again, and again ... 那就是那么是什么让你的应用程序写出“可爱的可爱的小狗”然后,再一次点燃事件,再次......

You could introduce a member variable _replacing which is set to true as long as the replacing takes place. 您可以引入成员变量_replacing ,只要进行替换,该变量_replacing设置为true When it's done, reset it to false . 完成后,将其重置为false

Now the only thing you have to do is to jump out of your code when the code is replacing: 现在,您唯一需要做的就是在代码替换时跳出代码:

If (_replacing) Then
    Return
End If

_replacing = True

txtMain.Text = Microsoft.VisualBasic.Strings.Replace(txtMain.Text, "Dog", "Cute Dog", 1, -1, Constants.vbTextCompare)
        txtMain.Select(txtMain.Text.Length, 0)

_replacing = False

With this, user input is still replaced but the changes from the replacement itself will not trigger the event again. 这样,用户输入仍然被替换,但替换本身的更改不会再次触发事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM