When a web application displays a string in a browser, due to the display length limitation, it is often necessary to intercept the string before display. However, many popular languages, such as C # and Java, use Unicode 16 (ucs2) encoding internally. In this encoding, all the characters are two characters. Therefore, if the string to be intercepted is a mix of Chinese, English, and numbers, the following string is generated:
String S = "A plus B equals C. If a equals 1 and B equals 2, C equals 3 ";
The preceding string contains both Chinese characters and English characters and numbers. If you want to intercept the first six bytes of characters, it should be "A plus B", but if you use the substring method to intercept the first six characters, it will be "A plus B equals C ". This problem occurs because the substring method treats double-byte Chinese characters as one byte character (ucs2 character. To solve this problem, first obtain the ucs2 encoded byte array of the string. The following code is as follows:
Byte [] bytes = system. Text. encoding. Unicode. getbytes (s );
Scanning starts from the first byte. For an English or numeric character, the first byte of ucs2 encoding is the corresponding ASCII, and the second byte is 0, for example, the ucs2 encoding of A is 97 0, and the two Chinese characters are not 0. Therefore, the ucs2 encoding rules can be used to calculate the actual number of bytes, register the string truncation method as an extension method of the string class. The implementation code is as follows:
Public static class stringext
{
Public static string bsubstring (this string S, int length)
{
Byte [] bytes = system. Text. encoding. Unicode. getbytes (s );
Int n = 0; // the current number of bytes.
Int I = 0; // number of bytes to intercept
For (; I <bytes. getlength (0) & n <length; I ++)
{
// The position of an even number, such as 0, 2, and 4, is the first byte of the two bytes in ucs2 encoding.
If (I % 2 = 0)
{
N ++; // Add 1 to n when the first byte of ucs2
}
Else
{
// When the second ucs2 encoding byte is greater than 0, the ucs2 character is a Chinese character. One Chinese character is counted as two bytes.
If (Bytes [I]> 0)
{
N ++;
}
}
}
// If I is an odd number, it is processed as an even number.
If (I % 2 = 1)
{
// When the ucs2 character is a Chinese character, remove the half Chinese Character
If (Bytes [I]> 0)
I = I-1;
// If the ucs2 character is a letter or number, the character is retained.
Else
I = I + 1;
}
Return System. Text. encoding. Unicode. getstring (bytes, 0, I );
}
}
In the above Code, if an odd number of characters (in bytes) are intercepted at the end, and the last character is a letter or number, the character is retained, if this Chinese character is half cut, the Chinese character is removed.
You can use the following code to intercept a string:
String substr = S. bsubstring (6); // The value of substr is "A plus B"