String类
//String类
//字符串字面值存在字符串池(方法区)中,可以共享
public class Text09 {
public static void main(String[] args) {
String name = "hello";//"hello"常量存在字符串池里面
name = "张珊";//"张珊"赋值给name,给字符串赋值时,并没有修改数据,而是重新开辟一个空间给"张珊",而"hello"被回收
String name2 = "张珊";//此时栈中的name/name2同时指向方法区中的"张珊";
//演示字符串的另一种创建方式
String str = new String("编程语言!");//这个是在堆里,也在方法区,会浪费空间
String str2 = new String("编程语言!");
System.out.println(str == str2);//这里比较的是地址。false
System.out.println(str.equals(str2));//这里比较的是值.true
System.out.println("======================================================");
//1.length():返回字符串长度
//2.charAt(int index);返回某个位置的字符
//3.contains(String str);判断是否包含某个字符串
String c = "最好的语言!最好一定是最好的么?";
System.out.println(c.length());
System.out.println(c.charAt(c.length() - 1));//获取最后一个位置的字符
System.out.println(c.contains("最好"));
System.out.println(c.contains("java"));
//4.toCharArray();返回字符串对应的数组
//5.indexOf():返回字符串首次出现的位置
//6.lastIndexOf():返回字符串最后依次出现的位置
System.out.println(Arrays.toString(c.toCharArray()));
System.out.println(c.indexOf("最好"));
System.out.println(c.indexOf("最好", 2));
System.out.println(c.lastIndexOf("最好"));
System.out.println("======================================================");
//7.trim():去掉字符串前后的空格
//8.toUpperCase():把小写转成大写; toLowerCase():把大写转成小写
//9.endWith():判断是否以str结尾; starWith():判断是否以str开头;
String s = " Hi! Leek!";
System.out.println(s.trim());
System.out.println(s.toUpperCase());
System.out.println(s.toLowerCase());
System.out.println(s.endsWith(""));//是否以空格开头,引号内无需添加任何元素
System.out.println(s.endsWith("!"));
//10.replace():将旧字符串转换成新字符串
//11.split():对字符串进行拆分
System.out.println(s.replace("Leek","YOO"));
String say="java is the be programing ,language?realy";
String[] arr=say.split("[ ,?]+");//若字符串中有其他字符(,?)则在引号内加上[,?];若还有多余的空格则填一个+号也能正常拆分
System.out.println(arr.length);
for(String string:arr){
System.out.println(string);
}
System.out.println("======================================================");
//补充两个方法equals、compare();比较大小
String s1="hello";
String s2="HELLO";
System.out.println(s1.equalsIgnoreCase(s2));//忽视大小写比较
String s3="abc";//97
String s4="xyz";//120
String s5="xyz003";//120
System.out.println(s3.compareTo(s4));//比较位置
System.out.println(s4.compareTo(s5));//比较长度
}
}
String 类案例演示:
public class Text09_1 {
public static void main(String[] args) {
String str ="this is a text";
//1.将str中的单词单独获取出来
String[] arr=str.split(" ");
for(String s:arr){
System.out.println(s);
}
//2.将str中的text替换为practice
String str2=str.replace("text","practice");
System.out.println(str2);
//3.在text前面加一个easy
String str3=str.replace("text","easy text");
System.out.println(str3);
//4.将每个单词的首字母改为大写
for (int i = 0; i < arr.length; i++) {
char first=arr[i].charAt(0);
char upperfirst=Character.toUpperCase(first);
System.out.println(upperfirst+arr[i].substring(1));
}
}
}