MCPcopy Create free account
hub / github.com/diyhi/bbs / bSubstring

Method bSubstring

src/main/java/cms/utils/StringUtil.java:85–110  ·  view source on GitHub ↗

按字节长度截取字符串 @param str 要截取的字符串 @param length 截取长度 @return @throws Exception

(String str, int length)

Source from the content-addressed store, hash-verified

83 * @throws Exception
84 */
85 public static String bSubstring(String str, int length) throws Exception{
86 byte[] bytes = str.getBytes("Unicode");
87 int n = 0; // 表示当前的字节数
88 int i = 2; // 要截取的字节数,从第3个字节开始
89 for (; i < bytes.length && n < length; i++){
90 // 奇数位置,如3、5、7等,为UCS2编码中两个字节的第二个字节
91 if (i % 2 == 1){
92 n++; // 在UCS2第二个字节时n加1
93 }else{
94 // 当UCS2编码的第一个字节不等于0时,该UCS2字符为汉字,一个汉字算两个字节
95 if (bytes[i] != 0){
96 n++;
97 }
98 }
99 }
100 // 如果i为奇数时,处理成偶数
101 if (i % 2 == 1){
102 // 该UCS2字符是汉字时,去掉这个截一半的汉字
103 if (bytes[i - 1] != 0)
104 i = i - 1;
105 // 该UCS2字符是字母或数字,则保留该字符
106 else
107 i = i + 1;
108 }
109 return new String(bytes, 0, i, "Unicode");
110 }
111
112 /**
113 * 清除前后空格&nbsp;

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected