1.String类
1.1String类概述
String 类代表字符串,Java 程序中的所有字符串文字(例如“abc”)都被实现为此类的实例。也就是说,Java 程序中所有的双引号字符串,都是 String 类的对象。String 类在 java.lang 包下,所以使用的时候不需要导包!
1.2String类的特点
- 字符串不可变,它们的值在创建后不能被更改
- 虽然 String 的值是不可变的,但是它们可以被共享
- 字符串效果上相当于字符数组( char[] ),但是底层原理是字节数组( byte[] )
1.3String类的构造方法
-
常用的构造方法
方法名 说明 public String() 创建一个空白字符串对象,不含有任何内容 public String(char[] chs) 根据字符数组的内容,来创建字符串对象 public String(byte[] bys) 根据字节数组的内容,来创建字符串对象 String s = “abc”; 直接赋值的方式创建字符串对象,内容就是abc -
示例代码
public class StringDemo01 { public static void main(String[] args) { //public String():创建一个空白字符串对象,不含有任何内容 String s1 = new String(); System.out.println("s1:" + s1); //public String(char[] chs):根据字符数组的内容,来创建字符串对象 char[] chs = {'a', 'b', 'c'}; String s2 = new String(chs); System.out.println("s2:" + s2); //public String(byte[] bys):根据字节数组的内容,来创建字符串对象 byte[] bys = {97, 98, 99}; String s3 = new String(bys); System.out.println("s3:" + s3); //String s = “abc”; 直接赋值的方式创建字符串对象,内容就是abc String s4 = "abc"; System.out.println("s4:" + s4); } }
1.4创建字符串对象两种方式的区别
-
通过构造方法创建
通过 new 创建的字符串对象,每一次 new 都会申请一个内存空间,虽然内容相同,但是地址值不同
-
直接赋值方式创建
以“”方式给出的字符串,只要字符序列相同(顺序和大小写),无论在程序代码中出现几次,JVM 都只会建立一个 String 对象,并在字符串池中维护
1.5字符串的比较
1.5.1==号的作用
- 比较基本数据类型:比较的是具体的值
- 比较引用数据类型:比较的是对象地址值
1.5.2equals方法的作用
-
方法介绍
public boolean equals(String s) 比较两个字符串内容是否相同、区分大小写 -
示例代码
public class StringDemo02 { public static void main(String[] args) { //构造方法的方式得到对象 char[] chs = {'a', 'b', 'c'}; String s1 = new String(chs); String s2 = new String(chs); //直接赋值的方式得到对象 String s3 = "abc"; String s4 = "abc"; //比较字符串对象地址是否相同 System.out.println(s1 == s2); System.out.println(s1 == s3); System.out.println(s3 == s4); System.out.println("--------"); //比较字符串内容是否相同 System.out.println(s1.equals(s2)); System.out.println(s1.equals(s3)); System.out.println(s3.equals(s4)); } }
1.5.3 String类常用方法
String类提供了许多方法来操作字符串,以下是一些常用的方法:
-
length():返回字符串的长度。int length = str.length(); -
charAt(int index):返回指定索引处的字符。char ch = str.charAt(0); // 'H' -
substring(int beginIndex, int endIndex):返回一个新的字符串,它是此字符串的一个子字符串。String sub = str.substring(0, 5); // "Hello" -
indexOf(String str):返回指定子字符串在此字符串中第一次出现处的索引。int index = str.indexOf("World"); // 7 -
replace(CharSequence target, CharSequence replacement):返回一个新的字符串,它是通过用新字符(串)替换此字符串中出现的所有旧字符(串)得到的。String newStr = str.replace("World", "Java"); -
toLowerCase()和toUpperCase():将字符串转换为小写或大写。String lowerStr = str.toLowerCase(); // "hello, world!" String upperStr = str.toUpperCase(); // "HELLO, WORLD!" -
trim():返回一个字符串,其值为此字符串,并删除了所有前导和尾随空白。String trimmedStr = " Hello ".trim(); // "Hello" -
split(String regex):根据给定正则表达式的匹配拆分此字符串。String[] parts = str.split(", "); // ["Hello", "World!"] -
equals(Object anObject):比较此字符串与指定对象是否相等。boolean isEqual = str.equals("Hello, World!"); // true -
startsWith(String prefix)和endsWith(String suffix):测试此字符串是否以指定的前缀或后缀开始或结束。boolean startsWith = str.startsWith("Hello"); // true boolean endsWith = str.endsWith("!"); // true