public MyString1 substring(int begin,int end) //提取子串{}
2 回答
慕沐林林
TA贡献2016条经验 获得超9个赞
不知道你说的实现是怎么个实现?如果只是调用的话 str.subString(begin,end)就可以了,如果是java的底层实现的话,下面是来自java.lang.String的代码:
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); } |
然后调用String的一个私有构造器:
// Package private constructor which shares value array for speed. String( int offset, int count, char value[]) { this .value = value; this .offset = offset; this .count = count; } |
莫回无
TA贡献1865条经验 获得超7个赞
给你个例子,你参考下
public class $ { public static void main(String[] args) { String str = "abcdefg" ; System.out.println(substring(str, 0 , 1 )); } private static String substring(String str, int begin, int end) { char [] ch = str.toCharArray(); StringBuffer buf = new StringBuffer(); for ( int i = begin; i < end; i++) { buf.append(ch[i]); } return buf.toString(); } } |
添加回答
举报
0/150
提交
取消