String类方法的使用:
**length():测试长度
trim():去掉字符串的前后空格
compareTo():比较第一个字母的数字相减
equalsIgnoreCase():指定对象比较,不考虑大小写
charAt():索引字符串的第几个字符是什么
indexOf():返回一个子串的索引
lastIndexOf():指定索引,从后往前找
substring():截取子串
startsWith():判断前缀后缀
endsWith():判断后缀
toUpperCase():大写
toLowerCase():小写
contains():包含否
valueOf():把各种数据类型转换为字符串的方法**
package cn_tedu_demo;
public class Demo {
public static void test1(){
String str =new String();
byte[] b ={97,98,99};
String str2 =new String(b);
System.out.println(str2);//abc
char[] c ={'1','b'};
System.out.println(new String(c));//1b
System.out.println(b);//[B@15db9742
System.out.println(c);//1b
}
//常用方法
public static void test2(){
//返回字符串的长度
System.out.println("hello".length());//5
//去掉字符串的前后空格
System.out.println(" he llo ".trim());//he llo
//equals.hashCode(),toString方法
//比较第一个字母的数字相减
System.out.println("abc".compareTo("bcd"));//-1
//指定对象比较,不考虑大小写
System.out.println("abc".equalsIgnoreCase("Abc"));//true
//charAt()
System.out.println("hello".charAt(2));//l
//indexof,返回一个子串的索引
System.out.println("hello".indexOf('e'));//返回索引位置:1
System.out.println("hello".indexOf("ellw"));//不存在字符串,返回为-1
System.out.println("hello".indexOf("l"));//2
//从3开始找
System.out.println("hello".indexOf("l",3));//3,在第三个的位置上找到
//lastIndexOf,指定索引,从后往前找
System.out.println("hello".lastIndexOf("1"));//-1,表示不存在
System.out.println("hello".lastIndexOf("l",4));//2
//subString(),截取子串
System.out.println("hello123".substring(2));//llo123
//包含索引,不包含[2,4),有2和3
System.out.println("hello123".substring(2,4));//ll
//判断前缀后缀
System.out.println("12345678999".startsWith("123"));//判断前缀是不是123,true
System.out.println("asdcvg0".endsWith("X"));//判断后缀是不是X,false
//大小写字符
System.out.println("aBxc".toUpperCase());//ABXC
System.out.println("ADBhsmx".toLowerCase());//adbhsmx
System.out.println("abcde".contains("cd"));//返回true表示包含,否则不包含 true
//valueOf,把各种数据类型转换为字符串的方法
System.out.println(String.valueOf(123));//123
char[] c ="abc".toCharArray();
}
public static void main(String[] args) {
//test1();
test2();
}
}