substring()和“==”

1.substring函数的两种用法:下标从0开始(1):只有一个参数,此参数为字符串截取开始位置;(2):两个参数,第一个为字符串截取开始位置,第二个为截取结束位置的下标,包含此下标前的字符串,不包含此下标。

2.在c++中,substr()函数也有两种用法:下标从0开始(1):只有一个参数,此参数为字符串截取开始位置;(2):两个参数,这里与java中的不同,第一个参数为字符串截取开始位置,第二个参数为要截取的字符串长度。

3.“==”判断左右字符串的内存存放位置是否相同, equals()判断左右字符串的内容是否相同。

这里需要注意:

“==”判断两字符串(一个为substring得到的字符串,一个为字符串常量)是否相等时,如果substring函数是从0开始截取,则两者相等,即是同一个字符串,位置也一样;如果不是从0截取,则substring实际上是拷贝了这个部分字符串,判断结果返回false。

如:

package corejava;

import static java.lang.Math.*;
public class CoreJava {
	
public static void main(String[] args) {
	String string="hello"	;
	
	if ("ello"==string.substring(1)) {
		System.out.println("true");
	}
	else{
		System.out.println("false\n");
	}
	if ("hello"==string.substring(0)) {
		System.out.println("从0截取true");
	}	
	else
	{
		System.out.println("从0截取全部false");
	}	 
}
}
 

结果:

我查看源码发现果然如此:从0截取,返回this;否则返回了一个new string();

所以源码很重要!!!

  /**
     * Returns a string that is a substring of this string. The
     * substring begins with the character at the specified index and
     * extends to the end of this string. <p>
     * Examples:
     * <blockquote><pre>
     * "unhappy".substring(2) returns "happy"
     * "Harbison".substring(3) returns "bison"
     * "emptiness".substring(9) returns "" (an empty string)
     * </pre></blockquote>
     *
     * @param      beginIndex   the beginning index, inclusive.
     * @return     the specified substring.
     * @exception  IndexOutOfBoundsException  if
     *             {@code beginIndex} is negative or larger than the
     *             length of this {@code String} object.
     */
    public String substring(int beginIndex) {
        if (beginIndex < 0) {
            throw new StringIndexOutOfBoundsException(beginIndex);
        }
        int subLen = value.length - beginIndex;
        if (subLen < 0) {
            throw new StringIndexOutOfBoundsException(subLen);
        }
        return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);
    }

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值