String类的常用方法
1.注意
String是一个不可变的类, 即一旦一个String对象被创建, 包含在这个对象中的字符序列是不可改变的, 直至该对象被销毁。
public class Test01 {
public static void main(String[] args) {
/**
* 知识点:String类的常用方法
* 注意:String是一个不可变的类, 即一旦一个String对象被创建, 包含在这个对象中的字符序列是不可改变的, 直至该对象被销毁。
*/
String str = "123abc";
str = str.concat("DEF123");//在此字符串末尾追加字符串,并返回新的字符串
str = str.substring(2);//从开始下标处截取到字符串末尾,并返回新的字符串
str = str.substring(1, 7);//从开始下标处(包含)截取到结束下标处(不包含),并返回新的字符串
str = str.toUpperCase();//转大写,并返回新的字符串
str = str.toLowerCase();//转小写,并返回新的字符串
str = " 123 a bcD EF 123 ";
str = str.trim();//去除首尾空格,并返回新的字符串
str = str.replace('2', '-');//替换字符,并返回新的字符串
str = str.replaceFirst("3", "林成");//替换第一个出现的字符串,并返回新的字符串
str = str.replaceAll("1", "xxx");//替换字符串,并返回新的字符串
str = str.replaceAll(" ", "");//替换字符串,并返回新的字符串
System.out.println("判断两个字符串内容是否相同:(区分大小写)" + str.equals("xxx-林成abcDEFxxx-3"));
System.out.println("判断两个字符串内容是否相同:(不区分大小写)" + str.equalsIgnoreCase("XXX-林成ABCdefxxx-3"));
System.out.println("判断此字符串是否以某个字符串开头:" + str.startsWith("xxx"));
System.out.println("判断此字符串是否以某个字符串结尾:" + str.endsWith("-3"));
System.out.println("查询此字符串第一次在目标字符串中的下标:" + str.indexOf("-"));
System.out.println("查询此字符串最后一次在目标字符串中的下标:" + str.lastIndexOf("-"));
System.out.println("获取指定下标上的字符:" + str.charAt(4));
//xxx-林成abcDEFxxx-3
System.out.println(str);
//将其他类型转换为字符串
int i = 100;
System.out.println(String.valueOf(i));
boolean bool = true;
System.out.println(String.valueOf(bool));
}
}
2.练习
完成一个邮箱格式的校验 hhy@qq.com
(1),“@”不能在第一位
(2),“.”不能在最后一位
(3),“@”和“.”中间应该有字符
(4),***@***.***
public class Test03 {
public static void main(String[] args) {
String email = "hhy@qq.com";
int index1 = email.indexOf("@");
int index2 = email.indexOf(".");
if(index1 == 0 || index2 == email.length()-1 || (index2-index1)<=1){
System.out.println("邮箱格式错误");
}
}
}
3.深入String创建对象问题
1.面试题1
下列代码创建几个String对象(考点:常量池中的值必须是唯一的)
String str1 = “abc”;
String str2 = “abc”;
答案:一个
2.面试题2
下列代码创建几个String对象(考点:常量池中的值必须是唯一的)
String str1 = new String(“abc”);
String str2 = new String(“abc”);
答案:三个
public class Test05 {
public static void main(String[] args) {
/**
* 知识点:深入String创建对象问题
*/
String str1 = "abc";
String str2 = "abc";
System.out.println(str1 == str2);//true
//两个常量字符串直接在编译时拼接
String str3 = "ab" + "c";
System.out.println(str3 == str1);//true
//两个常量字符串直接在编译时拼接
final String s1 = "ab";
final String s2 = "c";
String str4 = s1+s2;
System.out.println(str4 == str1);//true
//两个变量字符串拼接底层是创建StringBuilder对象
String s3 = "ab";
String s4 = "c";
String str5 = s3+s4;//new StringBuilder(s3).append(s4).toString()
System.out.println(str5 == str1);//false
}
}