Java语言进阶-常用类-String类

String的特性

  • String类:代表字符串。Java程序中的所有字符串字面值都为此类的实例对象
  • String类是一个final类,代表不可变的字符序列
  • 字符串是常量,用双引号括起来,他们的值在创建后就不能被更改
  • string对象的字符内容时存储在一个字符数组value[]上的
  • 实现了Serializable接口,表示字符串支持序列化
  • 实现了Comparable接口,表示字符串可以比较大小
import org.junit.Test;

public class StringTest{
    @Test
    public void test1(){
        String s1 = "abc";
        String s2 = "abc";

        System.out.println(s1 == s2);
        s1 = "hello";

        System.out.println(s1);
        System.out.println(s2);
    }
}

---------
true
hello
abc

如果你不假思索的就说出了这段程序运行的结果,你也许是小白,也许是大牛;如果你稍加思索说出了答案,表示你对栈堆方法区有一定理解。

字符串是一个常量,在创建s1,s2时,s1,s2两个标识符在栈中,“abc”这个常量在方法区中的常量池中,两个标识符都指向“abc”。如果我们对s1重新赋值,因为“abc”还有s2指向,所以会在常量池中再开辟一个放置“hello”的区域,此时s1指向“hello”,s2指向“abc”。

import org.junit.Test;

public class StringTest{
    @Test
    public void test1(){
        String s1 = "abc";
        String s2 = "abc";

        System.out.println(s1 == s2);
        s1 += "def";

        System.out.println(s1);
        System.out.println(s2);
    }
}
----------
true
abcdef
abc

s1+="def"同理,也是新建了一个常量。

import org.junit.Test;

public class StringTest{
    @Test
    public void test1(){
        String s1 = "abc";
        String s2 = s1.replace("a", "m");

        System.out.println(s1);
        System.out.println(s2);
    }
}

就算是换了一个下标上的字母,也是新建了一个常量,这就是字符串的不可变性。

字符串的创建

String str = "hello";

// 本质上是this.value = new char[0];
String s1 = new String();

// this.value = original.value;
String s2 = new String(String original);

// this.value = Arrays.copyOf(value,value.length);
String s3 = new String(char[] a);

String s4 = new String(char[] a,int startIndex,int count);

str的创建和s1是不一样的,前者是创建了一个常量,后者是new了一个对象。

import org.junit.Test;

public class StringTest{

    @Test
    public void test2(){
        String str = "ABC";

        String s1 = new String();
        String s2 = new String("ABC");

        char[] a = new char[]{'A','B','C'};
        String s3 = new String(a);

        String s4 = new String(a,1,2);

        System.out.println(str);
        System.out.println(s1);
        System.out.println(s2);
        System.out.println(s3);
        System.out.println(s4);
        
        System.out.println(str == s2);
        System.out.println(s2 == s3);
    }
}

虽然str,s2,s3字面值是一样的,但是他们都不相等。为了能够让他们进行对比,解决比较的问题,就引入了一个函数equals()

import org.junit.Test;

public class StringTest{

    @Test
    public void test2(){
        String str = "ABC";

        String s1 = new String();
        String s2 = new String("ABC");

        char[] a = new char[]{'A','B','C'};
        String s3 = new String(a);

        String s4 = new String(a,1,2);

        System.out.println(str);
        System.out.println(s1);
        System.out.println(s2);
        System.out.println(s3);
        System.out.println(s4);
        
        System.out.println(str.equals(s2));
        System.out.println(s2.equals(s3));
    }
}

Java小白修炼手册

字符串拼接对比

import org.junit.Test;

public class StringTest{

    @Test
    public void test3(){
        String s1 = "javaEE";
        String s2 = "hadoop";

        String s3 = "javaEEhadoop";
        String s4 = "javaEE" + "hadoop";
        String s5 = s1 + "hadoop";
        String s6 = "javaEE" + s2;
        String s7 = s1 + s2;
        String s8 = (s1 + s2).intern();

        System.out.println(s3 == s4);   // true
        System.out.println(s3 == s5);   // false
        System.out.println(s3 == s6);   // false
        System.out.println(s3 == s7);   // false
        System.out.println(s3 == s8);   // true
        System.out.println(s5 == s6);   // false
        System.out.println(s5 == s7);   // false
        System.out.println(s5 == s8);   // false
        System.out.println(s6 == s7);   // false
        System.out.println(s7 == s8);   // false
}

结论:

  • 常量与常量的拼接结果在常量池。且常量池中不会存在相同内容的常量。
  • 只要其中有一个是变量,结果就在堆中。
  • 如果拼接的结果调用intern()方法,返回值就在常量池中。

String常用方法

import org.junit.Test;

public class StringTest{
    @Test
    public void test4(){
        String s1 = " HelloWorld ";
        
        // length() 返回字符串的长度:return value.length
        System.out.println(s1.length());

        // charAt(int index) 返回某索引处的字符:return value[index]
        System.out.println(s1.charAt(2));

        // isEmpty() 判断是否是空字符串:return value.length == 0
        System.out.println(s1.isEmpty());

        // toLowerCase() 将String所有字符转换为小写,返回副本
        String s2 = s1.toUpperCase();
        System.out.println(s1);
        System.out.println(s2);

        // toUpperCase() 将String所有字符转换为大写,返回副本
        s2 = s1.toUpperCase();
        System.out.println(s1);
        System.out.println(s2);

        // trim() 去除字符串前后空格,返回副本
        s2 = s1.trim();
        System.out.println(s1);
        System.out.println(s2);

        // equals() 比较字符串的内容是否相同
        String s3 = " HelloWorld ";
        System.out.println(s1.equals(s3));

        // equalsIgnoreCase() 与equals方法类似,忽略大小写
        String s4 = " helloworld ";
        System.out.println(s1.equalsIgnoreCase(s4));

        // compareTo(String anotherString) 比较两个字符串的大小
        String s5 = "hello";
        System.out.println(s1.compareTo(s5));

        // subString(int beginIndex) 返回一个新字符串,从beginIndex处开始截取
        s2 = s1.substring(3);
        System.out.println(s2);

        // subString(int beginIndex,int endIndex) 返回一个新字符串,从beginIndex处开始截取,截取到endIndex
        s2 = s1.substring(3,7);
        System.out.println(s2);
        
        // endsWith(string suffix) 测试此字符串是否以指定的后缀结束
        boolean b1 = s1.endsWith("rld");
        System.out.println(b1);

        // startsWith(string prefix) 测试此字符串是否以指定的前缀开始
        b1 = s1.startsWith("hel");
        System.out.println(b1);

        // startsWith(string prefix,int toffset) 测试此字符串从指定索引开始的子字符串是否以指定的前缀开始
        b1 = s1.startsWith("lloW",3);
        System.out.println(b1);

        // contains(CharSequence s) 字符串中包含s序列时,返回true
        System.out.println(s1.contains(s5));
        
        // indexOf(String str) 返回指定子串在母串中的索引
        System.out.println(s1.indexOf("lo"));

        // indexOf(String str,int fromIndex) 返回指定子串在母串中第一次出现的位置的索引
        System.out.println(s1.indexOf("l",1));

        // lastIndexOf(String str) 返回指定子串在母串中最右边出现的索引
        System.out.println(s1.lastIndexOf("l"));

        //  lastIndexOf(String str,int fromIndex) 返回指定子串在母串中最右边第一次出现的位置的索引
        System.out.println(s1.lastIndexOf("l",4));

        // replace(char oldChar,char newChar) 使用newChar替换oldChar
        System.out.println(s1.replace("llo", "LLO"));

        // replace(CharSequence target,charSquence replacement) 使用指定的字面值替换字符串中所有匹配的子字符串
        String s6 = "L";
        System.out.println(s1.replace(s6, "l"));

        // replaceAll(String regex,String replacement) 使用指定的replacement替换字符串中所有匹配的子字符串
        String s7 = "1a2b3c4d5e";
        System.out.println(s7.replaceAll("\\d+", "l"));
    
        // replaceFirst(String regex,String replacement) 使用指定的replacement替换字符串中所有匹配的第一个子字符串
        System.out.println(s7.replaceFirst("\\d+", "l"));        
    
        // matches(String regex) 此字符串是否与正则表达式匹配
        String tel = "0571-234567";
        boolean result = tel.matches("0571-\\d{7,8}");
        System.out.println(result);

        // split(String regex) 根据给定的正则表达式拆分此字符串
        String s8 = "hello|world|java";
        String[] strs = s8.split("\\|");
        for(int i=0;i < strs.length;i ++){
            System.out.println(strs[i]);
        }

        // split(Strin regex,int limit) 根据给定的正则表达式拆分字符串,最多拆分limit个
        String[] strs1 = s8.split("\\|",2);
        for(int i=0;i < strs1.length;i ++){
            System.out.println(strs1[i]);
        }
    }
}

String类型转换

import java.io.UnsupportedEncodingException;
import java.util.Arrays;

import org.junit.Test;

public class StringTest {

    @Test
    public void test5() {
        String str1 = "abc123";
		// 将string转换为char[]
        char[] charArray = str1.toCharArray();
        for (int i = 0; i < charArray.length; i++) {
            System.out.println(charArray[i]);
        }

        char[] arr = new char[] { 'h', 'e', 'l', 'l', 'o' };
        // 将char[]转换为string
        String str2 = new String(arr);
        System.out.println(str2);
    }

    @Test
    public void test6() throws UnsupportedEncodingException {
        String str1 = "abc123";
		
        // 将字符串转换为byte[]
        byte[] bytes = str1.getBytes();
        System.out.println(Arrays.toString(bytes));
		
        // 将byte[]转换为字符串
        String str2 = new String(bytes);
        System.out.println(str2);

        byte[] gbks = str1.getBytes("gbk");
        System.out.println(Arrays.toString(gbks));

        str2 = new String(gbks);
        System.out.println(str2);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

寒 暄

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值