且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

文本框中的多个替换文本数据

更新时间:2023-02-23 14:49:18

是的.都是浪费时间.另外,如果存在多个值,则您的代码仅适用于这些值之一.只需将替换调用放在一个块中即可.摆脱循环.
Yes. It''s all a waste of time. Plus, your code just will work for one of these values, if more than one is there. Just put the Replace calls in a block. Get rid of the loop.
TextBox2.Text = Replace(TextBox2.Text, "kb", "kilobyte")
TextBox2.Text = Replace(TextBox2.Text, "mb", "megabyte")
TextBox2.Text = Replace(TextBox2.Text, "gb", "gigabyte")
TextBox2.Text = Replace(TextBox2.Text, "tb", "terabyte")



这就是您所需要的.另外,任何不带点的VB方法(因此InStr,而不是TextBox2.Text.Contains)都不要使用.之所以剩下这些,是因为VB6用户被认为太愚蠢,无法学习.NET.



That''s all you need. Also, any VB method that has no dot in it ( so InStr, instead of TextBox2.Text.Contains ), NEVER use. That''s stuff left in because VB6 users were presumed to be too stupid to learn .NET.


您可以将正则表达式与匹配评估器一起使用,并与字典(字典)结合使用会比您目前使用的技术提高性能):
You could use a regular expression with a match evaluator in combination with a dictionary (the dictionary will improve performance over the technique you are currently using):
Public Class Form1
    Private items As New Dictionary(Of String, String)
    Public Sub DoIt()
        items("x") = "the x"
        items("y") = "the y"
        items("z") = "the z"
        Dim pattern As String = "x|y|z"
        Dim reggy As New System.Text.RegularExpressions.Regex(pattern, _
            System.Text.RegularExpressions.RegexOptions.IgnoreCase)
        Dim input As String = "The x saw the y and z."
        Dim output As String = reggy.Replace(input, _
            New System.Text.RegularExpressions.MatchEvaluator(AddressOf ReplaceUnit))
    End Sub
    Private Function ReplaceUnit(ByVal match As _
        System.Text.RegularExpressions.Match) As String
        Return items(match.Value.ToLower())
    End Function
End Class