Convert a string to an ASCII array. If it is a Chinese byte code, it is ASCII code 63, that is "? ", So you can determine
Class StringOP
{
///
/// Obtain the actual length (in bytes) of the Chinese and English mixed string)
///
/// String to be retrieved
/// The actual length 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 ();
// Convert 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) // All Chinese characters are encoded as ASCII 63, that is "? "No.
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 + "the number of bytes is:" + iLen. ToString ());
Console. ReadKey ();
}
}
Converts a string to a byte array encoded in Unicode and determines whether the second byte of each character is greater than 0 to calculate the number of bytes of the string.
Public static int bytelenght (string str)
{
// Convert a string to a byte array using Unicode encoding. It 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 2 is obtained because all the elements in the byte array with double numbers are the first byte of the unicode character.
If (I % 2 = 0)
{
J ++;
}
Else
{
// The singular subscript is the 2nd bytes of the character. If the value of a single character's 2nd bytes is 0, the Unicode character is an English character. Otherwise, the Unicode character is a Chinese character.
If (bytestr [I]> 0)
{
J ++;
}
}
}
Return j;
}
Directly convert to bytecode to get the length:
Byte [] sarr = System. Text. Encoding. Default. GetBytes (s );
Int len = sarr. Length;