android 中String.trim()的使用

之前使用过字符串中trim()这个函数,没仔细去看这个函数到底有什么用,现在我查看了一些资料,终于明白这个函数的意思了。其实也比较简单,主要有2个用法:1、就是去掉字符串中前后的空白;这个方法的主要可以使用在判断用户输入的密码之类的。2、它不仅可以去除空白,还可以去除字符串中的制表符,如 ‘\t’,'\n'等。 下面贴一段注释:Returns a copy of the string, with leading and trailing whitespace omitted.

If this String object represents an empty character sequence, or the first and last characters of character sequence represented by this Stringobject both have codes greater than '\u0020' (the space character), then a reference to this String object is returned.

Otherwise, if there is no character with a code greater than '\u0020' in the string, then a new String object representing an empty string is created and returned.

Otherwise, let k be the index of the first character in the string whose code is greater than '\u0020', and let m be the index of the last character in the string whose code is greater than '\u0020'. A new String object is created, representing the substring of this string that begins with the character at index k and ends with the character at index m-that is, the result of this.substring(km+1).

This method may be used to trim whitespace (as defined above) from the beginning and end of a string.

Returns:A copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space. u\0020’之前的字符都会被清除,所以要保留\t,\n的要慎用trim()。

明白了后,我们再看一下贴出的原代码,返回的是没有制表符的的字符串,public String trim() {
        int start = offset, last = offset + count - 1;
        int end = last;
        while ((start <= end) && (value[start] <= ' ')) {
            start++;
        }
        while ((end >= start) && (value[end] <= ' ')) {
            end--;
        }
        if (start == offset && end == last) {
            return this;
        }
        return new String(start, end - start + 1, value);
    }。

如果我们在项目中,不需要去除2端的空白,只去除最右端的空白,则:

public String TrimRight(String sString){
		String sResult = "";
		
		if (sString.startsWith(" ")){
			sResult = sString.substring(0,sString.indexOf(sString.trim().substring(0, 1))
					+sString.trim().length());
		}
		else	sResult = sString.trim();
		
		return sResult;
	}
	好了,trim()方法介绍到这里了,也给自己多去了解一些底层的东西,这样才会对一个函数更加清楚和透彻,方便以后更好的应用。

你可能感兴趣的:(android 中String.trim()的使用)