public class StringTest {
public static void main(String[] args){
String s = "hello";
String s2 = "HELLO".toLowerCase();
System.out.println(s.equals(s2));//判断字符串是否相等,必须使用equals
System.out.println("HELLO".contains("LL"));//判断是否包含子字符串,返回布尔类型
System.out.println("Hello".indexOf("l"));//指定字符在字符串中第一次出现处的索引,如果没有,则返回-1
System.out.println("HELLO".lastIndexOf("L"));//指定字符在字符串中最后一次出现处的索引,如果没有,则返回-1
System.out.println("Hello".startsWith("He"));//判断字符串是否以指定的子字符开始。返回布尔类型
System.out.println("Hello".endsWith("lo"));//判断字符串是否以指定的子字符结束。返回布尔类型
System.out.println("Hello".substring(1));//截取子字符串从索引1开始到结束
System.out.println("Hello".substring(1,3));//提取子字符串从索引1开始到索引3结束,不包含索引3
System.out.println("\t\r\n hel lo ".trim());//移除字符串首尾空字符,包括空格,\t,\r,\n
System.out.println("".isEmpty());//判断字符串长度是否为0,为0则返回true
System.out.println(" ".isEmpty());//判断字符串长度是否为0,字符时为空则返回false,说明空白字符占字符长度
String h = "hello";
System.out.println(h.replace("l","L"));//替换子字符串,将所有的小写l替换为大写L
String s3 = "hello world!";
String[] ss = s3.split("l");//分割字符串,分割后是数组
System.out.println(s3.split("l")[0]);
String[] arr = {"A","B","C" };
System.out.println(String.join("*",arr));//拼接字符串
System.out.println(String.format("hi %s!you age is %d!your score is %.2f!","Bob",25,99.5));//格式化字符串
//要把任意基本类型或引用类型转换为字符串,可以使用静态方法valueOf()。这是一个重载方法,编译器会根据参数自动选择合适的方法
System.out.println(String.valueOf(123));//将int 123转换为字符串“123”
int n1 = Integer.parseInt("456"); //将字符串转换为整数456
System.out.println(n1);
boolean n2 = Boolean.parseBoolean("true");
System.out.println(n2); //将字符串转换为布尔类型true
char[] cs = "Hello".toCharArray(); //将String转换为char[]
String cc = new String(cs); // 将char[] -> String
System.out.println(cs[0]);
}
}