• String&StringBuilder&StringBuffer


    String字符串

    java.lang.String 类代表字符串。Java程序中所有的字符串文字(例如"abc" )都可以被看作是实现此类的实例。字符串是常量;它们的值在创建之后不能更改。字符串缓冲区支持可变的字符串。因为 String 对象是不可变的,所以可以共享。

    String 类包括的方法可用于检查序列的单个字符、比较字符串、搜索字符串、提取子字符串、创建字符串副本并将所有字符全部转换为大写或小写。

    Java 语言提供对字符串串联符号(“+”)以及将其他对象转换为字符串的特殊支持(toString()方法)。

    字符串的特点

    1、字符串String类型本身是final声明的,意味着我们不能继承String。

    2、字符串的对象也是不可变对象,意味着一旦进行修改,就会产生新对象

    我们修改了字符串后,如果想要获得新的内容,必须重新接受。

    如果程序中涉及到大量的字符串的修改操作,那么此时的时空消耗比较高。可能需要考虑使用StringBuilder或StringBuffer的可变字符序列。

    3、String对象内部是用字符数组进行保存

    JDK1.9之前有一个char[] value数组,JDK1.9之后byte[]数组

    "abc" 等效于 char[] data={ 'a' , 'b' , 'c' }

    例如: 
    String str = "abc";
    
    相当于: 
    char data[] = {'a', 'b', 'c'};     
    String str = new String(data);
    // String底层是靠字符数组实现的。
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    4、String类中这个char[] values数组也是final修饰的,意味着这个数组不可变,然后它是private修饰,外部不能直接操作它,String类型提供的所有的方法都是用新对象来表示修改后内容的,所以保证了String对象的不可变。

    5、就因为字符串对象设计为不可变,那么所以字符串有常量池来保存很多常量对象

    常量池在方法区。

    如果细致的划分:

    (1)JDK1.6及其之前:方法区

    (2)JDK1.7:堆

    (3)JDK1.8:元空间

    且需要注意从jdk1.7开始,常量池就移到堆内存中了,而在 JDK 1.8 中, HotSpot 已经没有 “PermGen space”这个区间了,取而代之的是 Metaspace(元空间)。
    
    • 1
    String s1 = "abc";
    String s2 = "abc";
    System.out.println(s1 == s2);
    // 内存中只有一个"abc"对象被创建,同时被s1和s2共享。
    
    • 1
    • 2
    • 3
    • 4

    字符串对象

    1、使用构造方法

    • public String() :初始化新创建的 String对象,以使其表示空字符序列。
    • String(String original): 初始化一个新创建的 String 对象,使其表示一个与参数相同的字符序列;换句话说,新创建的字符串是该参数字符串的副本。
    • public String(char[] value) :通过当前参数中的字符数组来构造新的String。
    • public String(char[] value,int offset, int count) :通过字符数组的一部分来构造新的String。
    • public String(byte[] bytes) :通过使用平台的默认字符集解码当前参数中的字节数组来构造新的String。
    • public String(byte[] bytes,String charsetName) :通过使用指定的字符集解码当前参数中的字节数组来构造新的String。

    构造举例,代码如下:

    //字符串常量对象
    String str = "hello";
    
    // 无参构造
    String str1 = new String();
    
    //创建"hello"字符串常量的副本
    String str2 = new String("hello");
    
    //通过字符数组构造
    char chars[] = {'a', 'b', 'c','d','e'};     
    String str3 = new String(chars);
    String str4 = new String(chars,0,3);
    
    // 通过字节数组构造
    byte bytes[] = {97, 98, 99 };     
    String str5 = new String(bytes);
    String str6 = new String(bytes,"GBK");
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    2、使用静态方法

    • static String copyValueOf(char[] data): 返回指定数组中表示该字符序列的 String(将数组中元素以字符串形式返回
    • static String copyValueOf(char[] data, int offset, int count):返回指定数组中表示该字符序列的 String(将数组中元素索引为offset到count的数据以字符串形式返回
    • static String valueOf(char[] data) : 返回指定数组中表示该字符序列的 String
    • static String valueOf(char[] data, int offset, int count) : 返回指定数组中表示该字符序列的 String
    • static String valueOf(xx value):xx支持各种数据类型,返回各种数据类型的value参数的字符串表示形式。(将xx类型的数据转换为字符串形式返回
    	public static void main(String[] args) {
    		char[] data = {'h','e','l','l','o','j','a','v','a'};	
    		String s1 = String.copyValueOf(data);
    		String s2 = String.copyValueOf(data,0,5);
    		int num = 123456;
    		String s3 = String.valueOf(num);
    		System.out.println(s1);
    		System.out.println(s2);
    		System.out.println(s3);
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    3、使用""+

    任意数据类型与"字符串"进行拼接,结果都是字符串

    	public static void main(String[] args) {
    		int num = 123456;
    		String s = num + "";
    		System.out.println(s);
    		
    		Student stu = new Student();
    		String s2 = stu + "";//自动调用对象的toString(),然后与""进行拼接
    		System.out.println(s2);
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    字符串的对象的个数

    1、字符串常量对象

    String str1 = "hello";//1个,在常量池中
    
    • 1

    2、字符串的普通对象和常量对象一起

    String str3 = new String("hello");
    //str3首先指向堆中的一个字符串对象,然后堆中字符串的value数组指向常量池中常量对象的value数组
    
    • 1
    • 2

    字符串拼接

    1、拼接结果的存储和比较问题

    原则:

    (1)常量+常量:结果是常量池

    (2)常量与变量 或 变量与变量:结果是堆

    (3)拼接后调用intern方法:结果在常量池

    • intern方法的作用是:判断字符串常量池中是否存在一个引用,这个引用指向的字符串对象和当前对象相等(使用 equals 方法判断相等),如果存在直接返回这个引用,如果不存在则创建一个字符串对象并将其引用存入字符串常量池。
    	@Test
    	public void test06(){
    		String s1 = "hello";
    		String s2 = "world";
    		String s3 = "helloworld";
    		
    		String s4 = (s1 + "world").intern();//把拼接的结果放到常量池中
    		String s5 = (s1 + s2).intern();
    		
    		System.out.println(s3 == s4);//true
    		System.out.println(s3 == s5);//true
    	}
    	
    	@Test
    	public void test05(){
    		final String s1 = "hello";
    		final String s2 = "world";
    		String s3 = "helloworld";
    		
    		String s4 = s1 + "world";//s4字符串内容也helloworld,s1是常量,"world"常量,常量+ 常量 结果在常量池中
    		String s5 = s1 + s2;//s5字符串内容也helloworld,s1和s2都是常量,常量+ 常量 结果在常量池中
    		String s6 = "hello" + "world";//常量+ 常量 结果在常量池中,因为编译期间就可以确定结果
    		
    		System.out.println(s3 == s4);//true
    		System.out.println(s3 == s5);//true
    		System.out.println(s3 == s6);//true
    	}
    	
    	@Test
    	public void test04(){
    		String s1 = "hello";
    		String s2 = "world";
    		String s3 = "helloworld";
    		
    		String s4 = s1 + "world";//s4字符串内容也helloworld,s1是变量,"world"常量,变量 + 常量的结果在堆中
    		String s5 = s1 + s2;//s5字符串内容也helloworld,s1和s2都是变量,变量 + 变量的结果在堆中
    		String s6 = "hello" + "world";//常量+ 常量 结果在常量池中,因为编译期间就可以确定结果
    		
    		System.out.println(s3 == s4);//false
    		System.out.println(s3 == s5);//false
    		System.out.println(s3 == s6);//true
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42

    2、拼接效率问题

    public class TestString {
    	public static void main(String[] args) {
    		String str = "0";
    		for (int i = 0; i <= 5; i++) {
    			str += i;  
    		}
    		System.out.println(str);      
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    3、两种拼接

    public class TestString {
    	public static void main(String[] args) {
    		String str = "hello";
    		String str2 = "world";
    		String str3 ="helloworld";
    		
    		String str4 = "hello".concat("world");
    		String str5 = "hello"+"world";
    		
    		System.out.println(str3 == str4);//false
    		System.out.println(str3 == str5);//true
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    concat方法拼接,哪怕是两个常量对象拼接,结果也是在堆。

    字符串对象的比较

    1、==:比较是对象的地址

    只有两个字符串变量都是指向字符串的常量对象时,才会返回true

    String str1 = "hello";
    String str2 = "hello";
    System.out.println(str1 == str2);//true
        
    String str3 = new String("hello");
    String str4 = new String("hello");
    System.out.println(str1 == str4); //false
    System.out.println(str3 == str4); //false
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    2、equals:比较是对象的内容,因为String类型重写equals,区分大小写

    只要两个字符串的字符内容相同,就会返回true

    String str1 = "hello";
    String str2 = "hello";
    System.out.println(str1.equals(str2));//true
        
    String str3 = new String("hello");
    String str4 = new String("hello");
    System.out.println(str1.equals(str3));//true
    System.out.println(str3.equals(str4));//true
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    3、equalsIgnoreCase:比较的是对象的内容,不区分大小写

    String str1 = new String("hello");
    String str2 = new String("HELLO");
    System.out.println(str1.equalsIgnoreCase(strs)); //true
    
    • 1
    • 2
    • 3

    4、compareTo:String类型重写了Comparable接口的抽象方法,自然排序,按照字符的Unicode编码值进行比较大小的,严格区分大小写

    String str1 = "hello";
    String str2 = "world";
    str1.compareTo(str2) //小于0的值
    
    • 1
    • 2
    • 3

    5、compareToIgnoreCase:不区分大小写,其他按照字符的Unicode编码值进行比较大小

    String str1 = new String("hello");
    String str2 = new String("HELLO");
    str1.compareToIgnoreCase(str2)  //等于0
    
    • 1
    • 2
    • 3

    空字符的比较

    String str1 = "";
    String str2 = new String();
    String str3 = new String("");
    
    • 1
    • 2
    • 3

    空字符串:长度为0

    2、判断某个字符串是否是空字符串

    if("".equals(str))
    
    if(str!=null  && str.isEmpty())
    
    if(str!=null && str.equals(""))
    
    if(str!=null && str.length()==0)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    String常用方法

    (1)boolean isEmpty():字符串是否为空

    (2)int length():返回字符串的长度

    (3)String concat(xx):拼接,等价于+(存储在堆)

    (4)boolean equals(Object obj):比较字符串是否相等,区分大小写

    (5)boolean equalsIgnoreCase(Object obj):比较字符串是否相等,区分大小写

    (6)int compareTo(String other):比较字符串大小,区分大小写,按照Unicode编码值比较大小

    (7)int compareToIgnoreCase(String other):比较字符串大小,不区分大小写

    (8)String toLowerCase():将字符串中大写字母转为小写

    (9)String toUpperCase():将字符串中小写字母转为大写

    (10)String trim():去掉字符串前后空白符

    	@Test
    	public void test01(){
    		//将用户输入的单词全部转为小写,如果用户没有输入单词,重新输入
    		Scanner input = new Scanner(System.in);
    		String word;
    		while(true){
    			System.out.print("请输入单词:");
    			word = input.nextLine();
    			if(word.trim().length()!=0){
    				word = word.toLowerCase();
    				break;
    			}
    		}
    		System.out.println(word);
    	}
    
    	@Test
    	public void test02(){
            //随机生成验证码,验证码由0-9,A-Z,a-z的字符组成
    		char[] array = new char[26*2+10];
    		for (int i = 0; i < 10; i++) {
    			array[i] = (char)('0' + i);
    		}
    		for (int i = 10,j=0; i < 10+26; i++,j++) {
    			array[i] = (char)('A' + j);
    		}
    		for (int i = 10+26,j=0; i < array.length; i++,j++) {
    			array[i] = (char)('a' + j);
    		}
    		String code = "";
    		Random rand = new Random();
    		for (int i = 0; i < 4; i++) {
    			code += array[rand.nextInt(array.length)];
    		}
    		System.out.println("验证码:" + code);
    		//将用户输入的单词全部转为小写,如果用户没有输入单词,重新输入
    		Scanner input = new Scanner(System.in);
    		System.out.print("请输入验证码:");
    		String inputCode = input.nextLine();
    		
    		if(!code.equalsIgnoreCase(inputCode)){
    			System.out.println("验证码输入不正确");
    		}
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44

    查找

    (11)boolean contains(xx):是否包含xx

    (12)int indexOf(xx):从前往后找当前字符串中xx,即如果有返回第一次出现的下标,要是没有返回-1

    (13)int lastIndexOf(xx):从后往前找当前字符串中xx,即如果有返回最后一次出现的下标,要是没有返回-1

    字符串截取

    (14)String substring(int beginIndex) :返回一个新的字符串,它是此字符串的从beginIndex开始截取到最后的一个子字符串。

    (15)String substring(int beginIndex, int endIndex) :返回一个新字符串,它是此字符串从beginIndex开始截取到endIndex(不包含)的一个子字符串。

    	@Test
    	public void test01(){
    		String str = "helloworldjavagec";
    		String sub1 = str.substring(5);
    		String sub2 = str.substring(5,10);
    		System.out.println(sub1);
    		System.out.println(sub2);
    	}
    
    	@Test
    	public void test02(){
    		String fileName = "快速学习Java的秘诀.dat";
    		//截取文件名
    		System.out.println("文件名:" + fileName.substring(0,fileName.lastIndexOf(".")));
    		//截取后缀名
    		System.out.println("后缀名:" + fileName.substring(fileName.lastIndexOf(".")));
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    字符相关

    (16)char charAt(index):返回[index]位置的字符

    (17)char[] toCharArray(): 将此字符串转换为一个新的字符数组返回

    (18)String(char[] value):返回指定数组中表示该字符序列的 String。

    (19)String(char[] value, int offset, int count):返回指定数组中表示该字符序列的 String。

    (20)static String copyValueOf(char[] data): 返回指定数组中表示该字符序列的 String

    (21)static String copyValueOf(char[] data, int offset, int count):返回指定数组中表示该字符序列的 String

    (22)static String valueOf(char[] data, int offset, int count) : 返回指定数组中表示该字符序列的 String

    (23)static String valueOf(char[] data) :返回指定数组中表示该字符序列的 String

    	@Test
    	public void test01(){
    		//将字符串中的字符按照大小顺序排列
    		String str = "helloworldjavagec";
    		char[] array = str.toCharArray();
    		Arrays.sort(array);
    		str = new String(array);
    		System.out.println(str);
    	}
    	
    	@Test
    	public void test02(){
    		//将首字母转为大写
    		String str = "jack";
    		str = Character.toUpperCase(str.charAt(0))+str.substring(1);
    		System.out.println(str);
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    开头与结尾

    (26)boolean startsWith(xx):是否以xx开头

    (27)boolean endsWith(xx):是否以xx结尾

    	@Test
    	public void test2(){
    		String name = "张三";
    		System.out.println(name.startsWith("张"));
    	}
    	
    	@Test
    	public void test(){
    		String file = "Hello.txt";
    		if(file.endsWith(".java")){
    			System.out.println("Java源文件");
    		}else if(file.endsWith(".class")){
    			System.out.println("Java字节码文件");
    		}else{
    			System.out.println("其他文件");
    		}
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    替换

    (29)String replace(xx,xx):不支持正则

    (30)String replaceFirst(正则,value):替换第一个匹配部分

    (31)String repalceAll(正则, value):替换所有匹配部分

    字符说明
    \将下一字符标记为特殊字符、文本、反向引用或八进制转义符。例如, n匹配字符 n\n 匹配换行符。序列 \\ 匹配 \\( 匹配 (
    ^匹配输入字符串开始的位置。如果设置了 RegExp 对象的 Multiline 属性,^ 还会与"\n"或"\r"之后的位置匹配。
    $匹配输入字符串结尾的位置。如果设置了 RegExp 对象的 Multiline 属性,$ 还会与"\n"或"\r"之前的位置匹配。
    *零次或多次匹配前面的字符或子表达式。例如,zo* 匹配"z"和"zoo"。* 等效于 {0,}。
    +一次或多次匹配前面的字符或子表达式。例如,"zo+"与"zo"和"zoo"匹配,但与"z"不匹配。+ 等效于 {1,}。
    ?零次或一次匹配前面的字符或子表达式。例如,"do(es)?“匹配"do"或"does"中的"do”。? 等效于 {0,1}。
    {n}n 是非负整数。正好匹配 n 次。例如,"o{2}"与"Bob"中的"o"不匹配,但与"food"中的两个"o"匹配。
    {n,}n 是非负整数。至少匹配 n 次。例如,"o{2,}“不匹配"Bob"中的"o”,而匹配"foooood"中的所有 o。"o{1,}“等效于"o+”。"o{0,}“等效于"o*”。
    {n,m}mn 是非负整数,其中 n <= m。匹配至少 n 次,至多 m 次。例如,"o{1,3}"匹配"fooooood"中的头三个 o。‘o{0,1}’ 等效于 ‘o?’。注意:您不能将空格插入逗号和数字之间。
    ?当此字符紧随任何其他限定符(*、+、?、{n}、{n,}、{n,m})之后时,匹配模式是"非贪心的"。"非贪心的"模式匹配搜索到的、尽可能短的字符串,而默认的"贪心的"模式匹配搜索到的、尽可能长的字符串。例如,在字符串"oooo"中,"o+?“只匹配单个"o”,而"o+“匹配所有"o”。
    .匹配除"\r\n"之外的任何单个字符。若要匹配包括"\r\n"在内的任意字符,请使用诸如"[\s\S]"之类的模式。
    (pattern)匹配 pattern 并捕获该匹配的子表达式。可以使用 $0…$9 属性从结果"匹配"集合中检索捕获的匹配。若要匹配括号字符 ( ),请使用"(“或者”)"。
    (?:pattern)匹配 pattern 但不捕获该匹配的子表达式,即它是一个非捕获匹配,不存储供以后使用的匹配。这对于用"or"字符 (|) 组合模式部件的情况很有用。例如,'industr(?:y|ies) 是比 ‘industry|industries’ 更经济的表达式。
    (?=pattern)执行正向预测先行搜索的子表达式,该表达式匹配处于匹配 pattern 的字符串的起始点的字符串。它是一个非捕获匹配,即不能捕获供以后使用的匹配。例如,‘Windows (?=95|98|NT|2000)’ 匹配"Windows 2000"中的"Windows",但不匹配"Windows 3.1"中的"Windows"。预测先行不占用字符,即发生匹配后,下一匹配的搜索紧随上一匹配之后,而不是在组成预测先行的字符后。
    (?!pattern)执行反向预测先行搜索的子表达式,该表达式匹配不处于匹配 pattern 的字符串的起始点的搜索字符串。它是一个非捕获匹配,即不能捕获供以后使用的匹配。例如,‘Windows (?!95|98|NT|2000)’ 匹配"Windows 3.1"中的 “Windows”,但不匹配"Windows 2000"中的"Windows"。预测先行不占用字符,即发生匹配后,下一匹配的搜索紧随上一匹配之后,而不是在组成预测先行的字符后。
    x|y匹配 xy。例如,‘z|food’ 匹配"z"或"food"。‘(z|f)ood’ 匹配"zood"或"food"。
    [xyz]字符集。匹配包含的任一字符。例如,"[abc]“匹配"plain"中的"a”。
    [^xyz]反向字符集。匹配未包含的任何字符。例如,"[^abc]“匹配"plain"中"p”,“l”,“i”,“n”。
    [a-z]字符范围。匹配指定范围内的任何字符。例如,"[a-z]"匹配"a"到"z"范围内的任何小写字母。
    [^a-z]反向范围字符。匹配不在指定的范围内的任何字符。例如,"[^a-z]"匹配任何不在"a"到"z"范围内的任何字符。
    \b匹配一个字边界,即字与空格间的位置。例如,“er\b"匹配"never"中的"er”,但不匹配"verb"中的"er"。
    \B非字边界匹配。“er\B"匹配"verb"中的"er”,但不匹配"never"中的"er"。
    \cx匹配 x 指示的控制字符。例如,\cM 匹配 Control-M 或回车符。x 的值必须在 A-Z 或 a-z 之间。如果不是这样,则假定 c 就是"c"字符本身。
    \d数字字符匹配。等效于 [0-9]。
    \D非数字字符匹配。等效于 [^0-9]。
    \f换页符匹配。等效于 \x0c 和 \cL。
    \n换行符匹配。等效于 \x0a 和 \cJ。
    \r匹配一个回车符。等效于 \x0d 和 \cM。
    \s匹配任何空白字符,包括空格、制表符、换页符等。与 [ \f\n\r\t\v] 等效。
    \S匹配任何非空白字符。与 [^ \f\n\r\t\v] 等效。
    \t制表符匹配。与 \x09 和 \cI 等效。
    \v垂直制表符匹配。与 \x0b 和 \cK 等效。
    \w匹配任何字类字符,包括下划线。与"[A-Za-z0-9_]"等效。
    \W与任何非单词字符匹配。与"[^A-Za-z0-9_]"等效。
    \xn匹配 n,此处的 n 是一个十六进制转义码。十六进制转义码必须正好是两位数长。例如,“\x41"匹配"A”。“\x041"与”\x04"&"1"等效。允许在正则表达式中使用 ASCII 代码。
    *num*匹配 num,此处的 num 是一个正整数。到捕获匹配的反向引用。例如,"(.)\1"匹配两个连续的相同字符。
    *n*标识一个八进制转义码或反向引用。如果 *n* 前面至少有 n 个捕获子表达式,那么 n 是反向引用。否则,如果 n 是八进制数 (0-7),那么 n 是八进制转义码。
    *nm*标识一个八进制转义码或反向引用。如果 *nm* 前面至少有 nm 个捕获子表达式,那么 nm 是反向引用。如果 *nm* 前面至少有 n 个捕获,则 n 是反向引用,后面跟有字符 m。如果两种前面的情况都不存在,则 *nm* 匹配八进制值 nm,其中 nm 是八进制数字 (0-7)。
    \nmln 是八进制数 (0-3),ml 是八进制数 (0-7) 时,匹配八进制转义码 nml
    \un匹配 n,其中 n 是以四位十六进制数表示的 Unicode 字符。例如,\u00A9 匹配版权符号 (©)。
    	@Test
    	public void test4(){
    		String str = "hello244world.java;887";
    		//把其中的非字母去掉
    		str = str.replaceAll("[^a-zA-Z]", "");
    		System.out.println(str);
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    String与可变字符序列的区别

    因为String对象是不可变对象,虽然可以共享常量对象,但是对于频繁字符串的修改和拼接操作,效率极低,所以JDK又在java.lang包提供了可变字符序列StringBuilder和StringBuffer类型。

    StringBuffer:老的,线程安全的

    StringBuilder:线程不安全的

    StringBuilder、StringBuffer的API

    常用的API,StringBuilder、StringBuffer的API是完全一致的

    (1)StringBuffer append(xx):拼接,追加

    (2)StringBuffer insert(int index, xx):在[index]位置插入xx

    (3)StringBuffer delete(int start, int end):删除[start,end)之间字符

    StringBuffer deleteCharAt(int index):删除[index]位置字符

    (4)void setCharAt(int index, xx):替换[index]位置字符

    (5)StringBuffer reverse():反转

    (6)void setLength(int newLength) :设置当前字符序列长度为newLength

    (7)StringBuffer replace(int start, int end, String str):替换[start,end)范围的字符序列为str

    (8)int indexOf(String str):在当前字符序列中查询str的第一次出现下标

          int indexOf(String str, int fromIndex):在当前字符序列[fromIndex,最后]中查询str的第一次出现下标
    
         int lastIndexOf(String str):在当前字符序列中查询str的最后一次出现下标
    
         int lastIndexOf(String str, int fromIndex):在当前字符序列[fromIndex,最后]中查询str的最后一次出现下标
    
    • 1
    • 2
    • 3
    • 4
    • 5

    (9)String substring(int start):截取当前字符序列[start,最后]

    (10)String substring(int start, int end):截取当前字符序列[start,end)

    (11)String toString():返回此序列中数据的字符串表示形式

    	@Test
    	public void test6(){
    		StringBuilder s = new StringBuilder("helloworld");
    		s.setLength(30);
    		System.out.println(s);
    	}
    	@Test
    	public void test5(){
    		StringBuilder s = new StringBuilder("helloworld");
    		s.setCharAt(2, 'a');
    		System.out.println(s);
    	}
    	
    	
    	@Test
    	public void test4(){
    		StringBuilder s = new StringBuilder("helloworld");
    		s.reverse();
    		System.out.println(s);
    	}
    	
    	@Test
    	public void test3(){
    		StringBuilder s = new StringBuilder("helloworld");
    		s.delete(1, 3);
    		s.deleteCharAt(4);
    		System.out.println(s);
    	}
    	
    	
    	@Test
    	public void test2(){
    		StringBuilder s = new StringBuilder("helloworld");
    		s.insert(5, "java");
    		s.insert(5, "chailinyan");
    		System.out.println(s);
    	}
    	
    	@Test
    	public void test1(){
    		StringBuilder s = new StringBuilder();
    		s.append("hello").append(true).append('a').append(12).append("gec");
    		System.out.println(s);
    		System.out.println(s.length());
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45

    对比测试

    /*
     * Runtime:JVM运行时环境
     * Runtime是一个单例的实现
     */
    public class TestTime {
    	public static void main(String[] args) {
    //		testStringBuilder();
    		testStringBuffer();
    //		testString();
    	}
    	public static void testString(){
    		long start = System.currentTimeMillis();
    		String s = new String("0");
    		for(int i=1;i<=10000;i++){
    			s += i;
    		}
    		long end = System.currentTimeMillis();
    		System.out.println("String拼接+用时:"+(end-start));//444
    		
    		long memory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
            System.out.println("String拼接+memory占用内存: " + memory);//53185144字节
    	}
        
    	public static void testStringBuilder(){
    		long start = System.currentTimeMillis();
    		StringBuilder s = new StringBuilder("0");
    		for(int i=1;i<=10000;i++){
    			s.append(i);
    		}
    		long end = System.currentTimeMillis();
    		System.out.println("StringBuilder拼接+用时:"+(end-start));//4
    		long memory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
            System.out.println("StringBuilder拼接+memory占用内存: " + memory);//1950488
    	}
        
    	public static void testStringBuffer(){
    		long start = System.currentTimeMillis();
    		StringBuffer s = new StringBuffer("0");
    		for(int i=1;i<=10000;i++){
    			s.append(i);
    		}
    		long end = System.currentTimeMillis();
    		System.out.println("StringBuffer拼接+用时:"+(end-start));//7
    		long memory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
            System.out.println("StringBuffer拼接+memory占用内存: " + memory);//1950488
    	}
    }
    /*
    String拼接+用时:396
    String拼接+memory占用内存: 477610752
    StringBuffer拼接+用时:1
    StringBuffer拼接+memory占用内存: 477610752
    StringBuilder拼接+用时:1
    StringBuilder拼接+memory占用内存: 477610752
    */
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55

    字符串对象不可变

    class TEXT{
    	public int num;
    	public String str;
    	
    	public TEXT(int num, String str){
    		this.num = num;
    		this.str = str;
    	}
    }
    public class Class4 {
        //tIn是传对象的地址,修改形参的属性,会影响实参
        //intIn是传数据,基本数据类型的形参修改和实参无关
        //Integer和String对象不可变
    	public static void f1(TEXT tIn, int intIn, Integer integerIn, String strIn){
    		tIn.num =200;
    		tIn.str = "bcd";//形参和实参指向的是同一个TEXT的对象,修改了属性,就相当于修改实参对象的属性
    		intIn = 200;//基本数据类型的形参是实参的“副本”,无论怎么修改和实参都没关系
    		integerIn = 200;//Integer对象和String对象一样都是不可变,一旦修改都是新对象,和实参无关
    		strIn = "bcd";
    	}
    	public static void main(String[] args) {
    		TEXT tIn = new TEXT(100, "abc");//tIn.num = 100, tIn.str="abc"
    		int intIn = 100;
    		Integer integerIn = 100;
    		String strIn = "abc";
    		
    		f1(tIn,intIn,integerIn,strIn);
    		
    		System.out.println(tIn.num + tIn.str + intIn + integerIn + strIn);
    		//200 + bcd + 100 + 100 + abc
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
  • 相关阅读:
    Linux安装MySQL8
    6.qml中js的object,array数据更新不通知页面刷新问题解析
    GhostNet网络解析
    【大数据】-- dataworks 创建odps 的 hudi 外表
    SpringBoot2.x仿B站项目的弹幕,投币系统可能的高并发数据缓存方面的学习笔记
    数字孪生应用及意义对电力的主要作用,概念价值。
    路由器——交换机——网络交换机:区别
    第五章 MyBais插件
    白帽SEO是什么?白帽SEO手法有哪些?
    云原生之Docker简介和环境准备
  • 原文地址:https://blog.csdn.net/yuqu1028/article/details/126091598