1.String类:即字符串类,其主要构造方法为:
String(String Original),把字符串封装成字符串对象;
举例:String a = new String(“hello”);
String(char[] value),把字符数组的数据封装成字符串对象;
举例:char[] b= {‘h’,‘e’,‘l’,‘l’,‘o’};
String c = new String(chs);
String(char[] value,int index, int count),从索引开始把字符数组值封装成字符串对象。
举例:char[] b = {‘h’,‘e’,‘l’,‘l’,‘o’};
String d = new String(chs,1,3);
最为简单的一种方法是直接构造法:
举例:String e = “hello”;
2.String代表不可变的字符序列,简称:不可变性
体现:1.当对字符串重新赋值时,需要重新指定内存区域赋值,不能使用原有的value进行赋值。
当对现有的字符串进行连接操作时,也需要重新指定内存区域赋值,不能使用原有的value进行 赋值。
3.当调用String的replace()方法修改指定字符或字符串时,也需要重新指定内存区域赋值,不能使 用原有的value进行赋值。
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=" a b c ";
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);
}