[Java] 02 String的常用方法

时间:2021-11-13 07:01:09
public class TestString{
public static void main(String[] args){
String str1 = "123";
String str2 = "456";
String str3 = "678";
StringBuilder sb1 = new StringBuilder();
//StringBuilder支持链式编程;
sb1.append(str1).append(str2);
StringBuilder sb2 = sb1;
sb2.append(str3);
System.out.println(sb1.toString());//123456678 //获取某个位置的字符,从0开始
System.out.println(sb1.charAt(3)); String str4 = "Hello";
//大写转小写
System.out.println(str4.toLowerCase());
//小写转大写
System.out.println(str4.toUpperCase());
//字符串长度
System.out.println(str4.length());// String str5 = "hello world";
//字符串替换
System.out.println(str5.replace("world","you"));//hello you
//替换原有字符串不会变
System.out.println(str5);// hello world
//是否以某个字符串开始
System.out.println(str5.startsWith("hello"));//ture
//是否以某个字符串结尾
System.out.println(str5.endsWith("you"));//false //希望获取一个文件的后缀 -->dadggtad.txt
String str6 = "t.txt";
//截取字符串
System.out.println(str6.substring(1,4));
//获取某字符串的位置
System.out.println(str6.indexOf("."));
System.out.println(str6.substring(str6.lastIndexOf(".")+1)); String word = "this is my world my name is Frost";
String[] strs = word.split(" ");
System.out.println(strs.length);
for(String str:strs){
System.out.println(str);
} String str7 = " dfajdfaj ;dfja ";
//去除字符串前面和后面的空格
System.out.println("|"+str7.trim()+"|");
}
}