Java基础--String类的trim方法

下面来自jdk中src/java/lang下的String类的trim()方法源码,反斜线//后面的部分为个人注释

 

public String trim() {
	int len = count;
	int st = 0;
	int off = offset;      /* avoid getfield opcode */
	char[] val = value;    /* avoid getfield opcode */

	while ((st < len) && (val[off + st] <= ' ')) {         //val[off + st] <=' '代表当数组中的值小于空格时
		st++;
	}
	while ((st < len) && (val[off + len - 1] <= ' ')) {    //同上
		len--;
	}
	return ((st > 0) || (len < count)) ? substring(st, len) : this;     //调用String类本身的substring方法
}

下面来自jdk中src/java/lang下的String类的substring方法原码

 

 

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类的构造方法
}

 

下面来自jdk中src/java/lang下的String类的构造方法String原码

 

public String(char value[], int offset, int count) {
	if (offset < 0) {
		throw new StringIndexOutOfBoundsException(offset);
	}
	if (count < 0) {
		throw new StringIndexOutOfBoundsException(count);
	}
	// Note: offset or count might be near -1>>>1.
	if (offset > value.length - count) {
		throw new StringIndexOutOfBoundsException(offset + count);
	}
	this.offset = 0;
	this.count = count;
	this.value = Arrays.copyOfRange(value, offset, offset+count);  //调用Arrays类的copyOfRange方法
}

下面来自jdk中src/java/util下的Arrays类的copyOfRange方法原码:

 

public static char[] copyOfRange(char[] original, int from, int to) {
	int newLength = to - from;
	if (newLength < 0)
		throw new IllegalArgumentException(from + " > " + to);
	char[] copy = new char[newLength];
	System.arraycopy(original, from, copy, 0,
			     Math.min(original.length - from, newLength));  //调用系统类的arraycopy方法
	return copy;
}


通过以上代码加深的以下几点内容的理解:

 

1.ASCII码是什么,特别对于本文中trim函数0-31,127为控制字符或者通信专用字符(不可显示),32-126(可显示)其中32代表空格。小于等于32的含义是将非可显字符和空格剔除,只留下可显字符。关于ASCII具体为什么可参考一下链接:

http://baike.baidu.com/view/15482.htm?fr=aladdin

2.对于为什么使用System类的arraycopy涉及到native方法相关问题,可查看前一天的文章(Java原码学习-String类的构造方法String(char value[]))。

 

一点猜想和疑问:

1.多个类中都有注释/** avoid getfield opcode **/,字面翻译过来是 “避免获取字段的字节码”,相关处理是一条赋值语句(例如:int len = count; int off = offset; char[]  val = value;)。但是为什么会出现按字面理解的有可能是获取到字节码,此处获取字节码的具体含义是什么?????(如果有高人了解,希望能留言指导,同时我也会继续搜寻这个问题,搞清答案后会更新此文)

 


版权声明:本文为lunda5原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。