中检测含有中文字符串的实际长度

 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;
}

  不过以上这段代码会比较慢一些

public int Text_Length(string Text)
{
int len=0;

for(int i=0;i<Text.Length;i++)
{
byte[] byte_len = Encoding.Default.GetBytes(Text.Substring(i,1));
if(byte_len.Length>1)
len += 2; //如果长度大于1,是中文,占两个字节,+2
else
len += 1; //如果长度等于1,是英文,占一个字节,+1
}

return len;
}

<script>
String.prototype.len=function(){
return this.replace(/[^\x00-\xff]/g,"**").length;
}
var str="我是zhiin";
alert(str.len())
</script>

用System.Text.Encoding.Default.GetByteCount(string)

public int GetStrLen(string str)
{
char[] StrLen = str.ToCharArray();
int len = str.Length();
if("是否中文长度".Length()==8)
{
return len;
}

for(int i=0;i<strLen.Length;i++)
{
if (strLen[i].ToInt32()>255)
len++;
}
return len;
}

你可能感兴趣的:(c,.net,prototype,vb,VB.NET)