//直接看API /** The value is used for character storage. */ private final char value[]; /** The offset is the first index of the storage that is used. */ private final int offset; /** The count is the number of characters in the String. */ private final int count; public String substring(int beginIndex) { return substring(beginIndex, count); } public String substring(int beginIndex, int endIndex) { if (beginIndex < 0) { throw new StringIndexOutOfBoundsException(beginIndex); } if (endIndex > count) { throw new StringIndexOutOfBoundsException(endIndex); } if (beginIndex > endIndex) { throw new StringIndexOutOfBoundsException(endIndex - beginIndex); } return ((beginIndex == 0) && (endIndex == count)) ? this : new String(offset + beginIndex, endIndex - beginIndex, value); }
只提供下思路好了
1 String转成char数组
2 取char数组的前length个元素组成新的数组
3 新的数组生成String
至于裸体跪求吗?
只提供下思路好了
1 String转成char数组
2 取char数组的第length个元素(从0开始)以后组成的新数组
3 新的数组生成String
String(char[] value, int offset, int count)
public class MyString { private String srcStr;
public MyString(String src) {
srcStr = src;
}
public String subString(int len) {
if (len < 0) return null;
if (len >= srcStr.length())
return new String(srcStr);
char[] buff = new char[len];
System.arraycopy(srcStr.toCharArray(), 0, buff, 0, buff.length);
return new String(buff);
}
public static void main(String[] args) {
System.out.println(new MyString("Hello, world!").subString(5));
}}
2 取char数组的第length个元素(从0开始)以后组成的新数组
3 新的数组生成String
//直接看API
/** The value is used for character storage. */
private final char value[]; /** The offset is the first index of the storage that is used. */
private final int offset; /** The count is the number of characters in the String. */
private final int count;
public String substring(int beginIndex) {
return substring(beginIndex, count);
}
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > count) {
throw new StringIndexOutOfBoundsException(endIndex);
}
if (beginIndex > endIndex) {
throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
}
return ((beginIndex == 0) && (endIndex == count)) ? this :
new String(offset + beginIndex, endIndex - beginIndex, value);
}
1、转换成char数组
2、new一个数组,长度是,原数组长度-length
3、使用System.arraycopy,copy数组数据
4、将char数组再转换成字符串不过觉得这个做法有点sb。绕了半天,最后还是这个结果。
咱们是学Java的啊。而Java是开源的啊。人家那是一堆人想的办法。或许别咱们一个人想的好。
呵呵.....我也是新手。共同学习哈!
2 取char数组的第length个元素(从0开始)以后组成的新数组
3 新的数组生成String
Object dest, int destPos,
int length);
如果有需要给你推荐一个老师:www.ldci.com.cn,找李老师,来自盛大的,呵呵