日期:2014-05-20 浏览次数:20841 次
import java.io.UnsupportedEncodingException; public class CutString { public static String substring(String orignal, int count)throws UnsupportedEncodingException { //原始字符不为null,也不是空字符串 if(orignal != null && !"".equals(orignal)) { // 将原始字符串转换为GBK编码格式 orignal = new String(orignal.getBytes(),"GBK"); // 要截取的字节数大于0,且小于原始字符串的字节数 if(count>0 && count<orignal.getBytes("GBK").length){ StringBuffer buff = new StringBuffer(); char c; int i=0; while(count > 0){ c = orignal.charAt(i); count -= String.valueOf(c).getBytes("GBK").length; if(count >= 0){ buff.append(c); } i++; } return buff.toString(); } } return orignal; } public static void main(String[] args) { String s = "我ABC汉DEF"; try { System.out.println(CutString.substring(s,5)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } }
------解决方案--------------------
这样行吗
public class Test20 { /** * @param args */ public String depart(String str,int i){ String str2=""; for(int j=0;j<i;j++){ System.out.println(str.charAt(j)); str2+=str.charAt(j); } return str2; } public static void main(String[] args) { // TODO Auto-generated method stub System.out.println(new Test20().depart("我是abcdef我", 5)); } }
------解决方案--------------------
这次应该对了
public class Test20 { /** * @param args */ public String depart(String str,int i){ String str2=""; for(int j=0;j<i;){ System.out.println(str.charAt(j)); str2+=str.charAt(j); if(str.charAt(j)>=0x4e00&&str.charAt(j)<0x9fa5){ j++; i--; } else{ j++; } if(i<j){ str2=str2.substring(0, j-1); } } return str2; } public static void main(String[] args) { // TODO Auto-generated method stub System.out.println(new Test20().depart("我ab是cdef我", 5)); } }
------解决方案--------------------
public String cutOutStr(String str,int byteNum){ if(str==null||str.getBytes().length<=byteNum){ return str; } int len = 0; StringBuilder sb = new StringBuilder(); for (Character ch : str.toCharArray()) { len = len + ch.toString().getBytes().length; if(len>byteNum){ break; } sb.append(ch); } return sb.toString(); }