以下就是在ASP.NET中检测含有中文字符串的实际长度,这个可能在很多地方都用的上.
VB.NET的写法:
Function StrLength(Byval Str As String) As Integer
Dim En As ASCIIEncoding=New ASCIIEncoding ()
Dim B As Byte()=En.GetBytes(Str)
Dim i As Integer=0
Dim Length As Integer=0
For i=0 To B.Length-1
If B(i)=63 Then
Length+=1
End If
Length+=1
Next
Return Length
End Function
以下是C#的写法:
function int StrLength(string Str)
{
ASCIIEncoding En=new ASCIIEncoding();
Byte[] B=En.GetBytes(Str);
int Length=0;
for(i=0;i<=B.Length-1;i++)
{
if(B==63)
{
Length+=1;
}
Length +=1;
}
return Length;
}
不过以上这段代码会比较慢一些