Converts a string to an ASCII-encoded array, so long as the Chinese byte code is ASCII code 63 that is "?", so it can be judged
Class Stringop
{
///
Gets the actual length of the mixed string in Chinese and English (in bytes)
///
String to get the length
The actual length value of the string (number of bytes)
public int getstringlength (string str)
{
if (str. Equals (String. Empty))
return 0;
int strlen = 0;
ASCIIEncoding strdata = new ASCIIEncoding ();
Converts a string to an ASCII-encoded byte number
byte[] strbytes = strdata.getbytes (str);
for (int i = 0; I <= strbytes.length-1; i++)
{
if (strbytes[i] = = 63)//Chinese will be encoded as ASCII encoding 63, that is, "?" Resolution
strlen++;
strlen++;
}
return strlen;
}
}
Class Testmain
{
static void Main ()
{
STRINGOP sop = new Stringop ();
String str = "I love china!" I love Beijing! ";
int ilen = sop.getstringlength (str);
Console.WriteLine ("string" + str + "Bytes is:" + ilen.tostring ());
Console.readkey ();
}
}
Converts a string to a byte array in Unicode encoding, determining whether the second byte of each character is greater than 0 to calculate the number of bytes in the string
public static int Bytelenght (String str)
{
Converts a string to a byte array using Unicode encoding, which stores all strings (including English and Chinese) in 2 bytes
byte[] bytestr = System.Text.Encoding.Unicode.GetBytes (str);
int j = 0;
for (int i = 0; i < Bytestr. GetLength (0); i++)
{
The remainder of 2 is because all even-numbered elements in the byte array are the first byte of the Unicode character
if (i% 2 = 0)
{
j + +;
}
Else
{
The singular subscript is the 2nd byte of the character, and if the 2nd byte of a character is 0, the Unicode character is the English character, otherwise the Chinese characters
if (Bytestr[i] > 0)
{
j + +;
}
}
}
Return J;
}
Convert directly to bytecode get length:
byte[] Sarr = System.Text.Encoding.Default.GetBytes (s);
int len = Sarr. Length;