String类总结
String类在Java中是很常见的,基础的就不多说了,这里总结一下String类常用的一些方法使用。
1.public int length()
这是很简单的获取字符串长度的函数。
2.public boolean equals(String s)
比较当前字符串的值与参数字符串的值是否相等。
先举例:String tom=new String("we are students");
String boy=new String("you are students");
String jerry=new String("we are students");
那么,tom.equals(boy)值是false,tom.equals(jerry)值为true。
这里需要注意的是,tom==jerry的值是false。因为equals()函数比较的是对象的值,而“==”比较的是对象本身。
3.public boolean startsWith(String s)、public boolean endsWith(String s)
startsWith(String s)方法判断当前字符串对象的前缀是否是参数指定的字符串,endsWith(String s)判断后缀。
Stringtom="abcdefg",
tom.startsWith("abc")的值为true, tom.endsWith("egf")的值为true。
4.public boolean regionMatches(int firstStart,String other,int ortherStart,int length)
从当前字符串参数firstStart指定的位置开始,取长度为length的一个子串,并将这个子串和参数other指定的字符串中从otherStart 指定的位置开始,取长度为length的一个子串进行比较,如果两个子串相同,则返回true,否则返回false。
5.public int compareTo(String s)
当前字符串按字符串与参数s指定的字符串比较大小。相同返回0,当前字符串大于s,返回正值,如果小于s,则返回负值。
String str="abcde"
str.compareTo("boy")小于0,str.compareTo("aba")大于0,str.compareTo("abcde")等于0.
6.public bollean contains(String s)
判断当前字符串是否含有指定的字符串s。
7.public int indexOf(String s)
从当前字符串的开头开始检索字符串s,并返回首次出现s的位置;如果没有检索到字符串s,返回的值是-1。
调用indexOf(String s,int startpoint)方法从当前字符串的startpoint位置处开始检索字符串s,并返回首次出现s的位置。
调用lastIndexOf(String s)方法从当前字符串的头开始检索字符串s,并返回最后出现s的位置。
String tom="I am a good cat"
tom.indexOf("a") //值为2
tom.indexOf("good",2) //值为7
tom.lastindexOf("a") //值为13
8.public String substring(int startpoint)
字符串调用该函数从当前字符串的startpoint处截取到最后得到一个子串。
调用substring(int start,int end)方法从当前字符串的start处截取到end处所得到的子串,但不包括end处所对应的字符。
String tom="I love java"
tom.substring(2,5) //所得子串为"lov"
9.public String trim()
当前字符串调用该函数得到当前字符串去掉前后空格的字符串。
10.public String toUpperCase()、public String toLowerCase()、public String concat(String str)
toUpperCase()函数把当前字符串中的小写字母变成大写字母;
toLowerCase()函数把当前字符串中的大写字母变成小写字母;
concat(String str)函数把当前字符串与参数字符串链接。
先整理这一些,等以后再见到再接着补充。。。