java String笔记

来源:互联网 发布:赵文卓甄子丹事件 知乎 编辑:程序博客网 时间:2024/05/21 02:35
子串(substring(a,b))

String greeting="Hello";

System.out.println(greeting.substring(0,3));//Hel

substring方法的第二个参数是不想复制的第一个位置。这里要复制的位置为0、1、2的字符。

此方法的工作方式有一个优点:容易计算子串的长度。例如s.substring(a,b)的长的为b-a

拼接
与绝大多数程序设计一样,Java语言允许使用+号连接两个字符串的操作。
String st1=“hello”;
String st2="world";
System.out.println(st1+st2);//helloworld
不可变字符串
String类没有提供修改字符串的方法。如果希望将gretting的内容修改为“Help”,不能直接将后两个字符修改为p(Strings are constant; their values cannot be changed after they are created.)。
检测字符串是否相等
public boolean equals(Object anObject)
Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
public boolean equalsIgnoreCase(String anotherString)
如果要检测两个字符串是否相等而不区分大小写,可以使用该方法。
Compares this String to another String, ignoring case considerations. Two strings are considered equal ignoring case if they are of the same length and corresponding characters in the two strings are equal ignoring case. 
一定不能使用==来检测两个字符串是否相等!这个运算符只能确定两个字符串是否放置在同一个位置上。当然,若果字符串放置在同一个位置上,他们必然相等。但是,完全有可能将内容相同的多个字符串的拷贝放置在不同的位置上。
String greeting="Hello";/initialize greeting to a string
if(greeting=="Hello")
//probably true
if(greeting.substring(0,3)=="Hel")
//probably false
如果虚拟机始终将相同的字符串共享,就可以使用==运算符来检测是否相等。而实际上只有字符串常量是共享的,而+或substring等操作产生的结果并不是共享的。因此
千万不要使用==运算符来测试字符串的想等性,以免在程序中出现糟糕的bug。表明上看这种bug很像随机产生的间歇性错误。

原创粉丝点击