Java关于空字符串的正确判断

Java字符串操作坑
本文通过一个具体的Java示例,展示了如何正确使用字符串的子串方法,并对比了两种不同的字符串比较方式,强调了在进行字符串操作时需要注意的问题。

有时候真的学艺不精。。。

故做此篇,以警之。


public class Test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String first = "ni'hao'";
		String third = null;
//		System.out.println("-->" + first.lastIndexOf("'") + "<--"+ first.length());
		
		//好不靠谱
		if ( (first.substring(first.lastIndexOf("'") + 1)!="") ) {
			third = first.substring(first.lastIndexOf("'") + 1);
			System.out.println("-->" + third + "<--");
		} else {
			System.out.println("err");
		}
		
		//可靠
		if ( !(first.substring(first.lastIndexOf("'") + 1).equals("")) ) {
			third = first.substring(first.lastIndexOf("'") + 1);
			System.out.println("-->" + third + "<--");
		} else {
			System.out.println("err");
		}

	}

}


输出结果:

--><--
err

结果显而易见,两种比较,完全是不同的。。。

顺便留心一下 substring()方法和给出的例子:

public String substring(int beginIndex)
Returns a new 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.

Examples:

 "unhappy".substring(2) returns "happy"
 "Harbison".substring(3) returns "bison"
 "emptiness".substring(9) returns "" (an empty string)

an empty string!

有时候一不留神就跳坑了,警示一下




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值