.net 如何将 stringbuilder 与字符串进行比较 [英] .net how to compare a stringbuilder to a string
问题描述
在 vb.net(或 C#)中,我不知道如何将 stringbuilder 与字符串进行比较.我已经搜索了很多,但找不到答案.我必须编写自己的例程.没有更好的方法吗?
In vb.net (or C#) I can't figure out how to compare a stringbuilder to a string. I have searched quite a bit and can't find the answer. I had to write my own routine. Isn't there a better way?
这不起作用:
Dim s As String = "abc"
Dim sb As New StringBuilder("abc")
If sb.Equals(s) Then
Console.WriteLine(sb.ToString() + " DOES equal " + s)
Else
Console.WriteLine(sb.ToString() + " does NOT equal " + s)
End If
该代码的结果是:abc 不等于 abc
Results of that code is: abc does NOT equal abc
是否有某种方法可以在不编写自己的例程的情况下将 stringbuilder 与 string 进行比较?很明显我遗漏了一些东西,因为我在任何地方都找不到这个问题.
Isn't there some way of comparing a stringbuilder to a string without writing my own routine? It's probably something obvious that I'm missing since I can't find this question anywhere.
推荐答案
最简单的方法是将 StringBuilder
的内容作为字符串获取:
The simplest way is to get the content of the StringBuilder
as a string:
If sb.ToString() = s Then ...
如果您想避免创建该字符串(可能是出于内存使用问题),恐怕您必须编写自己的例程来比较它们.基本上是这样的:
If you want to avoid creating that string (perhaps for memory usage concerns), I am afraid that you have to write your own routine to compare them. Basically something like:
Public Shared Function SbEquals(sb As StringBuilder, s As String) As Boolean
If sb.Length <> s.Length Then Return False
For i As Integer = 0 to s.Length - 1
If sb(i) <> s(i) Return False
Next
Return True
End Function
这篇关于.net 如何将 stringbuilder 与字符串进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!