VB.NET中字符串中的字符替换 [英] Character replacement in strings in VB.NET

查看:71
本文介绍了VB.NET中字符串中的字符替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

替换字符串中字符的速度有多快?

How fast can I replace characters in a string?

所以这个问题的背景是这样的:我们有几个应用程序通过套接字相互通信并与客户端的应用程序通信.这些套接字消息包含不可打印的字符(例如 chr(0)),需要用预定的字符串(例如{Nul}"})替换,因为套接字消息保存在日志文件中.顺便说一句,不是每条日志消息都需要替换字符.

So the background on this question is this: We have a couple of applications that communicate with each other and with clients' applications through sockets. These socket messages contain non-printable characters (e.g. chr(0)) which need to get replaced with a predetermined string (e.g "{Nul}"}, because the socket messages are kept in a log file. On a side note, not every log message will need to have characters replaced.

现在我开始阅读这个 MSDN 链接,这是我从本网站的另一篇文章中找到的.

Now I started off on this little adventure reading from this MSDN link which I found from a different post from this site.

我们使用的当前方法...在一天开始时...使用 StringBuilder 来检查所有可能的替换,例如...

The current method we used...at the beginning of the day...was using StringBuilder to check for all the possible replacements such as...

    Public Function ReplaceSB(ByVal p_Message As String) As String
      Dim sb As New System.Text.StringBuilder(p_Message)

      sb.Replace(Chr(0), "{NUL}")
      sb.Replace(Chr(1), "{SOH}")

      Return sb.ToString
    End Function

现在,正如博客文章指出的那样,将 StringBuilder 排除在外并使用 string.replace 确实会产生更快的结果.(实际上,使用 StringBuilder 是整天执行此操作最慢的方法.)

Now as the blog post points out leaving StringBuilder out and using string.replace does yield faster results. (Actually, using StringBuilder was the slowest method of doing this all day long.)

    p_Message = p_Message.Replace(Chr(0), "{NUL}")
    p_Message = p_Message.Replace(Chr(1), "{SOH}")

我知道并不是每条消息都需要经过这个过程,我认为不必处理那些可能被遗漏的消息会节省时间.所以使用正则表达式我首先搜索字符串,然后确定是否需要处理它.这与使用 string.replace 大致相同,基本上节省了不处理所有字符串的时间,但浪费了使用正则表达式检查所有字符串的时间.

Knowing that not every message would need to go through this process I thought it would save time to not have to process those messages that could be left out. So using regular expressions I first searched the string and then determined if it needed to be processed or not. This was about the same as using the string.replace, basically a wash from saving the time of not processing all the strings, but losing time from checking them all with regular expressions.

然后建议尝试使用一些将其索引与新旧索引匹配的数组,并使用它来处理消息.所以它会是这样的......

Then it was suggested to try using some arrays that matched up their indexes with the old and the new and use that to process the messages. So it would be something like this...

Private chrArray() As Char = {Chr(0), Chr(1)}
Private strArray() As String = {"{NUL}", "{SOH}"}

Public Function TestReplace(ByVal p_Message As String) As String
    Dim i As Integer

    For i = 0 To ((chrArray.Length) - 1)
        If p_Message.Contains(chrArray(i).ToString) Then
            p_Message = p_Message.Replace(chrArray(i), strArray(i))
        End If
    Next

    Return p_Message
End Function

这是迄今为止我发现的处理这些消息的最快方法.我尝试了各种其他方法来解决这个问题,例如将传入的字符串转换为字符数组并进行比较,还尝试遍历字符串而不是 chrArray.

This so far has been the fastest way I have found to process these messages. I have tried various other ways of going about this as well like converting the incoming string into a character array and comparing along with also trying to loop through the string rather than the chrArray.

所以我对所有人的问题是:我可以让它更快吗?我错过了什么?

So my question to all is: Can I make this faster yet? What am I missing?

推荐答案

您或许可以通过减少一些查找来提高速度.举个例子:

You might be able to squeeze out a little more speed by reducing some lookups. Take for example this:

    If p_Message.Contains(chrArray(i).ToString) Then

.Contains 方法是 O(n).在最坏的情况下,您将遍历整个字符串中的所有字符而没有找到任何内容,因此您希望为数组中的每个字符至少遍历一次,因此它的 O(nm) 其中 n 是长度您的字符串和 m 是您要替换的字符数.

The .Contains method is O(n). In the worst case, you're going to traverse all the chars in the entire string without finding anything, so you expect to traverse at least one time for each character in your array, so its O(nm) where n is the length of your string and m is the number of chars you're replacing.

执行以下操作可能会获得更好的性能(我的 VB-fu 已生锈,尚未经过测试;)):

You might get a little better performance doing the following (my VB-fu is rusty, has not been tested ;) ):

Private Function WriteToCharList(s as String, dest as List(Of Char))
    for each c as Char in s
        dest.Add(c)
    Next
End Function

Public Function TestReplace(ByVal p_Message As String) As String
    Dim chars as new List(Of Char)(p_Message.Length)

    For each c as Char in p_Message
        Select Case c
            Case Chr(0): WriteToCharList("{NUL}", chars)
            Case Chr(1): WriteToCharList("{SOH}", chars)
            Case Else: chars.Add(c);
        End Select
    Next

    Return New String(chars)
End Function

这将最多遍历 p_Message 中的字符两次(一次用于遍历,一次是在字符串构造函数复制字符数组时),使该函数 O(n).

This will traverse chars in p_Message at most twice (once for traversing, once when the string constructor copies the char array), making this function O(n).

这篇关于VB.NET中字符串中的字符替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆