String类的常用方法介绍
通过java API可以看出,String类的方法特别多,但不需要全部记住,有些方法用到的时候查一下就可以,而常用的方法需要我们记住!
public String(byte[] bytes):把字节数组转换成一个字符串
常用方法
1. 求字符串长度
public int length() //返回该字符串的长度
2. 求字符串某一位置字符
public char charAt(int index) //返回字符串指定位置的字符
3. 提取字串
1)public String substring(int beginIndex) //该方法从beginIndex位置起,从当前字符串中取出剩余的字符作为一个新的字符串返回
2)public String substring(int beginIndex,int endIndex) //该方法从beginIndex位置起,从当前字符串中取出到endIndex-1位置的字符作为一个新的字符串返回
4. 字符串比较
1)public int compareTo(String str) //该方法是对字符串内容按字典顺序进行大小比较,通过返回的整数值指明当前字符串与参数字符串的大小关系。若当前对象比参数大则返回正整数,反之返回负整数,相等返回0
2)public int compareToIgnore(String str) //与上述方法类似,但忽略大小写
3)public boolean equals(Object o) //比较当前字符串和参数字符串,相等 返回true,否则返回false
4)public boolean equalsIgnoreCase(String str) // 与上述方法类似,但忽略大小写
5. 字符串连接
public String concat(String str) //将参数中的字符串str连接到当前字符串的后面,效果等价于“+”
6. 字符串中单个字符查找
1)public int indexOf(int ch/String str) //用于查找当前字符串中字符或子串,返回字符或子串在当前字符串中从左边起首次出现的位置,若没有返回-1
2)public int indexOf(int ch/String str,int fromIndex) //该方法与上述类似,区别在于该方法从fromIndex位置向后查找
3)public int lastIndexOf(int ch/String str) //该方法与第一种方法类似,区别在于该方法从字符串的末尾向前查找
4)public int lastIndexOf(int ch/String str,int fromIndex) //该方法与第二种方法类似,区别在于该方法从fromIndex位置向前查找
7. 字符串中字符的大小写转换
1)public String toLowerCase() //返回将当前字符串中所有字符转换成小写后的新串
2)public String toUpperCase() //返回将当前字符串中所有字符转换成大写后的新串
8. 字符串中字符的替换
1)public String replace(char oldChar,char newChar) //用字符newChar替换当前字符串中所有的oldChar字符,并返回一个新的字符串
2)public String replaceFirst(String regex,String replacement) //用字符串replacement替换当前字符串中遇到的第一个和字符串regex相匹配的字串,并返回一个新的字符串
3)public String replaceALL(String regex,String replacement) //用字符串replacement替换当前字符串中遇到的所有和字符串regex相匹配的字串,并返回一个新的字符串
9. 其他方法
1)String trim() //截去字符串两端的空格,但对于中间的空格不处理
2)boolean startsWith(String prefix)或boolean endWith(String suffix) //判断此字符串是否以参数字符(串)开始 或 结尾
3)boolean regionMatches(boolean b,int firstStart,String other.int otherStart,int length) //从当前字符串的firstStart位置开始取长度为length的一个子字符串,与other字符串从otherStart位置开始取长度为length的字符串作比较,当b为true时,字符串不区分大小写
4)boolean contains(String str) //判断参数是否包含在字符串中
5)String[] split(String str) //将str作为分隔符进行字符串分解,分解后的子字符串在字符串数组中返回
10.字符串与其它基本类型的转换
1.字符串转换为基本类型
java.lang包中有Byte、Short、Integer、Float、Double类的调用方法:
1)public static byte parseByte(String s)
2)public static short parseShort(String s)
3)public static int parseInt(String s)
4)public static long parseLong(String s)
5)public static float parseFloat(String s)
6)public static double parseDouble(String s)
2.基本类型转换为字符串
String类中提供了String valueOf()方法,用作基本数据类型转换为字符串类型
1)static String valueOf(char data[])
2)static String valueOf(char data[],int offset,int count)
3)static String valueOf(boolean b)
4)static String valueOf(char c)
5)static String valueOf(int i)
6)static String valueOf(long l)
7)static String valueOf(float f)
8)static String valueOf(double d)