String表示字符串,用来存储字符串数据
字符串是常量,它们的值在创建之后不能更改
只要使用String赋值后,这个字符串会一直在内存中存在如果改变字符串的值,不是改变内存中的这个个字符串,应为它具有不变性,而是重新创建或找到一个相同的字符串更改地址引用
经常变化的字符串不推荐使用String定义,变化一次就会在内存中重新创建一个字符串,java有一个强大的垃圾回收机制自动方释放垃圾资源
byte类型转换为字符串
public static void main(String[] args) {
String s1="abc";//引用内存中ABC字符串的地址
String s2=new String();//创建一个空字符串
byte[] bytes1={97,98,99,100,101,102};//byte范围是-128—127
String s3=new String(bytes1);//把byte数组中的整数值
byte[] bytes2={97,98,99,100,101,102,103,104};//照ASCII码表解析abcdefgh
String s4=new String(bytes2,2,3);//把byte数组中的整数值,从索引2的元素开始截取3个长度,按照ASCII码表解析成字符串
char[] chars1={'a','b','c','d','e'};
String s5=new String(chars1);//把字符串数组转换成字符串
char[] chars2={'a','b','c','d','e'};
String s6=new String(chars2,2,2);//把字符串数组从索引2的元素开始截取2个长度转换成字符串
String s7=new String("abcd");
System.out.println("==========");
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s4);
System.out.println(s5);
System.out.println(s6);
System.out.println(s7);
}
String类的方法
public static void main(String[] args) {
String s1="abcdefgh";
char c=s1.charAt(2);//获取字符串中指定索引位置的元素
System.out.println(c);
String s2=s1.concat("xyz");//字符串的拼接,把是字符串拼接上xyz
System.out.println(s2);
boolean b1=s1.contains("x");//是否包含某个字符串
boolean b2=s2.contains("x");
System.out.println(b1);
System.out.println(b2);
String s3="javaTest.txt";
boolean b3=s3.endsWith(".txt");//判断字符串是否以。TXT结束,常常用来判断文件名的后缀
System.out.println(b3);
String s4="abcd";
byte[] bytes1=s4.getBytes();//把字符串按照ASCII码表解析成byte数组
char[] chars1=s4.toCharArray();//把字符串按照ASCII码表转换成字符数组
String s5="Bad weather fuck the weather";
String s6=s5.replace("fuck","***");//把字符串fuck替换为***
System.out.println(s6);
String s7="abcdefg";
String s8=s7.substring(2,5);//截取字符串,从第2个索引开始截取到第5个索引,不包含第5个索引
System.out.println(s8);
String s9="2022-12-02";
String[] split=s9.split("-");//按照-拆分字符串形成字符串数组[2022-12-02]
for(String s:split){
System.out.println(s);
}
String s10=" 面 包 ";
System.out.println(s10);
String s11=s10.trim();//去除字符串前后的空格
System.out.println(s11);
String s12="abcde";
int a1= s12.indexOf("a");
System.out.println(a1);
String s13="xyz";
int a2=s13.indexOf("x");
System.out.println(a2);
String s14="djfbfdjb";
int a3=s14.lastIndexOf("b");
System.out.println(a3);
String s15="ABCDEFGH";
String s16=s15.toLowerCase();
System.out.println(s16);
String s17="jdbdgdmdhb";
String s18=s17.toUpperCase();
System.out.println(s18);
}