编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。 但是要保证汉字不被截半个。
2016-06-26 17:19
543 查看
public class TestSplitString {
public static String splitString(String str,int byteNum) throws Exception {
char[] c = str.toCharArray();
System.out.println(Arrays.toString(c));
return new String(c,0,getToIndex(c, byteNum));
}
public static int getToIndex(char[] c,int byteNum) throws Exception{
int num = 0;
for(int i = 0;i < c.length;i++){
num += ((c[i] + "").getBytes("gb2312")).length;
if(num >= byteNum)
return i + 1;
if(i + 1 == c.length)
return c.length;
}
return 0;
}
public static void main(String[] args) throws Exception {
System.out.println(splitString("我ABC们DEF",9));
}
}
public static String splitString(String str,int byteNum) throws Exception {
char[] c = str.toCharArray();
System.out.println(Arrays.toString(c));
return new String(c,0,getToIndex(c, byteNum));
}
public static int getToIndex(char[] c,int byteNum) throws Exception{
int num = 0;
for(int i = 0;i < c.length;i++){
num += ((c[i] + "").getBytes("gb2312")).length;
if(num >= byteNum)
return i + 1;
if(i + 1 == c.length)
return c.length;
}
return 0;
}
public static void main(String[] args) throws Exception {
System.out.println(splitString("我ABC们DEF",9));
}
}
相关文章推荐
- Android之获取手机上的图片和视频缩略图thumbnails
- android string.xml文件中的整型和string型代替
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- android上改变listView的选中颜色
- String.intern
- Mootools 1.2教程 函数
- autoit InputBox 函数
- 文件遍历排序函数
- Prototype源码浅析 String部分(二)
- Ruby中的String对象学习笔记
- 关于C#中排序函数的总结
- Oracle 函数大全[字符串函数,数学函数,日期函数]第1/4页
- ASP下经常用的字符串等函数参考资料
- PostgreSQL教程(五):函数和操作符详解(1)
- C#中struct和class的区别详解
- DOS批处理 函数定义与用法
- asp Chr 函数 数字转字母的方法
- Lua中的函数精讲笔记
- Lua中的闭合函数、非全局函数与函数的尾调用详解