您的位置:首页 > 编程语言 > Java开发

java和Js 按字节来截取字符串长度(为了符合数据库varchar)

2011-07-21 15:33 489 查看
/**
* 截取符合oracle varchar长度的字符集
*
* @author 陈兵
*
*/
public class SplitString {

public static String subStringByByte(String str,int byteNum) throws Exception {
byte bt[] = str.getBytes();
System.out.println(" Length of this String ===> " + bt.length );
if (byteNum >= 1) {
if (byteNum > bt.length ){
String substrx = new String(bt, 0, bt.length);
return substrx;
} else{
String substrex = new String(bt, 0, byteNum);
return substrex;
}
} else {
System.out.println("输入错误!!!请输入大于零的整数:");
throw new Exception();
}

}

public static void main(String[] args){

String str = "我我我ABC汉DEF我我我ABC汉DEF我我我ABC汉DEF我我我ABC汉DEF我我我ABC汉DEF我我我ABC汉DEF我我我ABC汉DEF我我我ABC汉DEF我我我ABC汉DEF我我我ABC汉DEF我我我ABC汉DEF我我我ABC汉DEF我我我ABC汉DEF我我我ABC汉DEF我我我ABC汉DEF我我我ABC汉DEF我我我ABC汉DEF";
for(int i=1;i<=100;i++){
try {
String res = subStringByByte(str, i);
System.out.println(res);
} catch (Exception e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
}

}
}
JS的截取方法:
function substr(str, len)
{
if( ! str || ! len)
{
return '';
}
// 预期计数:中文2字节,英文1字节
var a = 0;
// 循环计数
var i = 0;
// 临时字串
var temp = '';
for (i = 0; i < str.length; i ++ )
{
if (str.charCodeAt(i) > 255)
{
// 按照预期计数增加2
a += 2;
}
else
{
a ++ ;
}
// 如果增加计数后长度大于限定长度,就直接返回临时字符串
if(a > len)
{
return temp;

}
// 将当前内容加到临时字符串
temp += str.charAt(i);
}
// 如果全部是单字节字符,就直接返回源字符串
return str;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: