上周某公司笔试时遇到的题目,题目描述如下:
编程题
编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。 但是要保证汉字不被截半个,如“我ABC”4,应该截为“我AB”,输入“我ABC汉DEF”,6,应该输出为“我ABC”而不是“我ABC+汉的半个”。
这道题目的关键点有两个:
1、汉字按照2字节,英文字母按照1字节进行截取(需要找到对应的编码格式)
2、如何判断哪个是汉字,哪个是英文字母(需要找到区分汉字与字母的方法)
关于编码格式(参考文章),哪种编码能符合题目的要求呢,请看下面(参考文章):
Java代码 
- import java.io.UnsupportedEncodingException;
-
- public class EncodeTest {
-
-
-
-
-
-
-
-
- public static void printByteLength(String s, String encodingName) {
- System.out.print("字节数:");
- try {
- System.out.print(s.getBytes(encodingName).length);
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- System.out.println(";编码:" + encodingName);
- }
-
- public static void main(String[] args) {
- String en = "A";
- String ch = "人";
-
-
- System.out.println("英文字母:" + en);
- EncodeTest.printByteLength(en, "GB2312");
- EncodeTest.printByteLength(en, "GBK");
- EncodeTest.printByteLength(en, "GB18030");
- EncodeTest.printByteLength(en, "ISO-8859-1");
- EncodeTest.printByteLength(en, "UTF-8");
- EncodeTest.printByteLength(en, "UTF-16");
- EncodeTest.printByteLength(en, "UTF-16BE");
- EncodeTest.printByteLength(en, "UTF-16LE");
-
- System.out.println();
-
-
- System.out.println("中文汉字:" + ch);
- EncodeTest.printByteLength(ch, "GB2312");
- EncodeTest.printByteLength(ch, "GBK");
- EncodeTest.printByteLength(ch, "GB18030");
- EncodeTest.printByteLength(ch, "ISO-8859-1");
- EncodeTest.printByteLength(ch, "UTF-8");
- EncodeTest.printByteLength(ch, "UTF-16");
- EncodeTest.printByteLength(ch, "UTF-16BE");
- EncodeTest.printByteLength(ch, "UTF-16LE");
- }
- }
运行结果如下:
- 英文字母:A
- 字节数:1;编码:GB2312
- 字节数:1;编码:GBK
- 字节数:1;编码:GB18030
- 字节数:1;编码:ISO-8859-1
- 字节数:1;编码:UTF-8
- 字节数:4;编码:UTF-16
- 字节数:2;编码:UTF-16BE
- 字节数:2;编码:UTF-16LE
- 中文汉字:人
- 字节数:2;编码:GB2312
- 字节数:2;编码:GBK
- 字节数:2;编码:GB18030
- 字节数:1;编码:ISO-8859-1
- 字节数:3;编码:UTF-8
- 字节数:4;编码:UTF-16
- 字节数:2;编码:UTF-16BE
- 字节数:2;编码:UTF-16LE
可知,GB2312、GBK、GB18030三种编码格式都符合题目要求
如何判断哪个字符是中文,哪个是字母,可能有很多种方法,仁者见仁吧
一种,可以将字符串转化为字符数组,分别检查字符的GBK形式的字节长度
另一种,可以按照指定的字节数截取对应长度的字符串,然后判断子串的字节长度是否等于指定截取的字节长度,等于的话,说明子串没有中文,不等于的话,说明有中文字符。
请看相关代码:
Java代码 
-
-
-
-
-
-
-
-
-
- public static boolean isChineseChar(char c)
- throws UnsupportedEncodingException {
-
-
- return String.valueOf(c).getBytes("GBK").length > 1;
- }
Java代码 
-
-
-
-
-
-
-
-
-
- public static String subStr(String str, int subSLength)
- throws UnsupportedEncodingException
- {
-
- if (str == null)
- return null;
- else
- {
- int tempSubLength = subSLength;
-
- String subStr = str.substring(0, subSLength);
-
- int subStrByetsL = subStr.getBytes("GBK").length;
-
-
- while (subStrByetsL > tempSubLength)
- {
- subStr = str.substring(0, --subSLength);
- subStrByetsL = subStr.getBytes("GBK").length;
- }
- return subStr;
- }
-
- }