如何通过勾选复选框替换字符串中的对应位置字符
问题原因
你的代码每次触发替换逻辑时,都是基于未修改的原始字符串Label9.Text做替换,然后直接覆盖Label8.Text的内容。如果多个复选框同时勾选,靠前的复选框生成的替换结果会被靠后的复选框的替换结果完全覆盖,最终只会保留最后一个生效的复选框的修改效果。
修正代码
你需要先把原始字符串赋值给一个临时变量,所有替换操作都基于这个临时变量修改,全部替换完成后再把最终结果赋值给Label8.Text,代码如下:
' 先把原始字符串存入临时变量 Dim targetStr As String = Label9.Text If CheckBox1.Checked Then targetStr = targetStr.Replace(targetStr.Substring(1, 2), ComboBox2.Text) End If If CheckBox2.Checked Then targetStr = targetStr.Replace(targetStr.Substring(15, 2), word) End If If CheckBox5.Checked Then targetStr = targetStr.Replace(targetStr.Substring(13, 2), ComboBox5.Text) End If If CheckBox8.Checked Then targetStr = targetStr.Replace(targetStr.Substring(2, 1), ComboBox6.Text.Substring(1, 1)) End If ' 所有替换完成后统一赋值 Label8.Text = targetStr
优化建议
String.Replace方法会替换字符串中所有匹配的子串,如果你要替换的子串在字符串其他位置也有相同内容,会出现误替换。更稳妥的按位置替换写法可以直接拼接字符串:
' 按位置替换示例:替换索引1开始的2个字符 targetStr = targetStr.Remove(1,2).Insert(1, ComboBox2.Text)
内容的提问来源于stack exchange,提问作者pankaj babbar
相关产品推荐
相关产品推荐

