- package com.javatest;
- public class String_SubTest {
- /**
- * 2个字节存储一个中文,一个字节存储一个英文字母,一个字节数为256
- *
- * @param args
- */
- public String substring(String str, int subByte)// 参数为一个字节数,另一个为字节数
- {
- int count = 0;
- for (int i = 0; i < str.length(); i++) {
- if (count == subByte) {
- return str.substring(0, i);
- }
- char c = str.charAt(i);
- if (c < 256) {
- count++;
- } else {
- count += 2;
- if (count - subByte == 1) {
- return str.substring(0, i);
- }
- }
- }
- return str;
- }
- public static void main(String[] args)
- {
- String str=new String_SubTest().substring("我ABC汉DEF",6 );
- System.out.println(str);
- }
- }
输出结果为:我ABC