public class Demo01 {public static void main(String[] args) { System.out.println(Demo01.StringCut("中国你好abcdef", 0, 7)); } public static String StringCut(String str,int from,int to){ byte[] a = str.getBytes(); byte[] b = new byte[to-from]; //将a数组里从索引为from的元素开始, //复制到数组b里的索引为0的位置, 复制的元素个数为to-from个. System.arraycopy(a, from, b, 0, to-from); String newStr = new String(b); return newStr; } }
输入结果:中国你?
public class InterceptString { public static void main(String args[]) { InterceptString is = new InterceptString(); String str = "少一些功利***的追求,多一些不为什么的坚持!" ; System.out.println(is.stringCut(str,0,10)); } public String stringCut(String str,int start,int end) { byte[] strByte = str.getBytes(); byte[] newstrByte = new byte[end - start]; System.arraycopy(strByte, start, newstrByte, 0, end - start); String cutStr = new String(newstrByte); return cutStr; } }
public String mySubString(String inputString, int from, int to) throws UnsupportedEncodingException { // TODO Auto-generated method stub byte[] bytes = inputString.getBytes("UTF-8"); int size = to; if(to > bytes.length) { size = bytes.length; } byte[] resultBytes = new byte[size - from]; int j = 0; for (int i = from; i < size; i++) { resultBytes[j] = bytes[i]; j++; } return new String(resultBytes, "UTF-8"); }
public static void main(String[] args) throws UnsupportedEncodingException { String str1 = "asd阿达"; int start = 2; int end = 5; byte[] bytes = str1.getBytes("GBK"); byte[] newByte = new byte[end - start]; System.arraycopy(bytes, start,newByte, 0, end-start); String newStr = new String(newByte, "GBK"); System.out.println(newStr); }
public class Main { public static void main(String[] args) { String str = "中国加油!"; System.out.println(bytecut(str,2,10)); } public static String bytecut(String str,int starttId, int endId){ byte[] bytestr = str.getBytes(); byte[] newbytestr = new byte[endId-starttId]; for(int i=1;i<=endId-starttId;i++){ newbytestr[i-1]=bytestr[i+starttId-1]; } String newstr = new String(newbytestr); return newstr; } }