String类型(详述)

目录

1、引言

2、String类

2.1、String的本质

2.2、String初始化构造方法

2.3、String常用判断功能方法 

2.4、 String常用转换功能方法 

2.5、String常用获取功能方法

2.6、String分割、替换、去空格、正则功能 

2.7、常量池

3、StringBuilder、StringBuffer类

3.1初始化StringBuilder类

3.2、append和insert添加方法

3.3、delete删除方法

3.4、replace替换方法

3.5、reverse反转方法

4、StringBuilder和String相互转换

 5、StringBuilder,StringBuffer和String区别

6、字符串拼接案例


1、引言

在我之间的文章中讲述了八大基本数据类型之间的类型转换,没有讲解String类的类型转换,这期就补充一下String类型。

2、String类

 String是一个类,代表字符串。String类的值会被存放到常量池中,所以String的值是不能被改变的,String是可以被所有对象所共享。

2.1、String的本质

1、JDK8之前底层是char[] 数组来实现的。

2、JDK8之后底层是byte[] 数组来实现的。

2.2、String初始化构造方法

方法名说明
public String()初始化新创建的String对象,以使其表示空字符序列
public String(char[] value)通过当前参数中的字符数组来构造新的String。
String(char[] value, int offset, int count)通过当前参数中的字符数组的一部分来构造新的String。
String(byte[] bytes)通过使用平台的默认字符集解码当前参数中的字节数组来构造新的
String(byte[] bytes, int offset, int length)通过使用平台的默认字符集解码当前参数中的字节数组的一部分来构造新的String
public class PersonTest {
    public static void main(String[] args) {
        Person p1 =new Person("李四",25);
        Person p2 =new Person("李四",25);
        Person p3 =new Person("李四",25);
        int num1=23;
        int num2=23;
        System.out.println("姓名:"+p1.getName()+" 年龄:"+p1.getAge());

        p1.setName("王五");
        p1.setAge(36);
        System.out.println("姓名:"+p1.getName()+" 年龄:"+p1.getAge());

        System.out.println(p1==p2);//false  ==比较引用类型的地址值  比较基本类型的值
        System.out.println(p1.getAge()==p2.getAge());
        System.out.println(num1==num2);

        System.out.println(p3.equals(p2));//不重写equals方法比较地址  重写后比较字符串内的值
    }
}

 

2.3、String常用判断功能方法 

方法名说明
boolean equals(Object obj)比较字符串的内容是否相同,区分大小写
boolean equalsIgnoreCase(String str)比较字符串的内容是否相同,忽略大小写
boolean contains(String str)       判断大字符串中是否包含小字符串
boolean startsWith(String str)判断字符串是否以某个指定的字符串开头
boolean endsWith(String str)判断字符串是否以某个指定的字符串结尾
boolean isEmpty()判断字符串是否为空
public class StringDemo {
    public static void main(String[] args) {
        String s1="hello";
        String s2="hello";
        String s3="helloWorld";
        String s4="helloworld";

        System.out.println("equals:"+s1.equals(s2));//true
        System.out.println("equals:"+s1.equals(s3));//false
        System.out.println("-----------------------");
        System.out.println(s3.equalsIgnoreCase(s4));//true
        System.out.println("-----------------------");
        System.out.println(s3.contains("llo"));//true
        System.out.println(s3.contains("lw"));//false  一定是连在一起的
        System.out.println("-----------------------");
        System.out.println(s3.startsWith("hell"));//true
        System.out.println("-----------------------");
        System.out.println(s4.endsWith("ld"));//true
        System.out.println("-----------------------");
        String a="";
        System.out.println(a.isEmpty());//true
        String b=null;
        System.out.println(b.isEmpty());//报错  空指针异常
        
    }
}

2.4、 String常用转换功能方法 

方法名说明
public char[] toCharArray()将此字符串转换为新的字符数组。
public byte[] getBytes()使用平台的默认字符集将该String编码转换为新的字节数组。
public String replace(char oldChar, char newChar)将oldChar匹配的字符串使用newChar字符串替换
public String replaceFirst(String regex,String replacement)用给定的 replacement 替换此字符串匹配给定的regex的第一个子字符串。
public String toUpperCase()将字符中转换为大写
public String toLowerCase()将字符中转换为小写
public class StringTest3 {
    public static void main(String[] args) {
        String s="javaSE";
        //把字符串转换为字节数组
        byte[] bytes = s.getBytes();
        for (int i = 0; i <bytes.length ; i++) {
            System.out.println(bytes[i]);
        }
        //把字符串转换为字符数组
        char[] chars = s.toCharArray();
        for (int i = 0; i <chars.length ; i++) {
            System.out.print(chars[i]);
        }
        System.out.println();
        //把字符数组转换为字符串数组
        char[] chars1={'a','b','d','e'};
        String s1 = String.valueOf(chars1);
        System.out.println(s1);
        //把int类型转换为字符串
        int i=60;
        String s2 = String.valueOf(i);
        System.out.println(s2);
        //把字符串转换为小写
        System.out.println("toLowerCase:"+s.toLowerCase());
        //把字符串转换为大写
        System.out.println("toUpperCase:"+s.toUpperCase());


        String ss1="hello";
        String ss2="world";
        //第一种方式拼接
        System.out.println(ss1+ss2);
        //第二种方式拼接
        System.out.println(ss1.concat(ss2));

    }
}

 

2.5、String常用获取功能方法

方法名说明
public int length()返回此字符串的长度
public String concat(String str)将指定的字符串连接到该字符串的末尾
public char charAt(int index)返回指定索引处的char值         
public int indexOf(int ch)返回指定子字符串第一次出现在该字符串内的索引
public String substring(int beginIndex)返回一个子字符串,从beginIndex开始截取字符串到字符串结尾
public String substring(int beginIndex,int endIndex)         返回一个子字符串,从beginIndex到endIndex截取字符串。含beginIndex,不含endIndex
public class StringTest {
    public static void main(String[] args) {
        String s = "helloWorld";
        System.out.println("length:"+s.length());//获取字符串的长度
        System.out.println("------------------------");
        System.out.println("charAt:"+s.charAt(5));//W  获取指定位置的字符
        System.out.println("------------------------");
        System.out.println("indexOf:"+s.indexOf('o'));//4  返回第一次字符出现的位置
        System.out.println("indexOf:"+s.indexOf('o',5));//6  返回指定索引以后的字符出现的位置
        System.out.println(s.indexOf('l',40));//-1 找不到的话就返回-1
        System.out.println("------------------------");
        System.out.println(s.substring(5));//从此索引处开始截取后面的字符串
        System.out.println(s.substring(2,6));//从此索引处开始截取后面的字符串,包左不包右
        System.out.println(s.substring(0,s.length()));//全部输出字符串

    }
}

2.6、String分割、替换、去空格、正则功能 

方法名说明
public String[] split(String regex)将此字符串按照给定的regex(规则)拆分为字符串数组
public String trim()去除该字符串的两端空格
public boolean  matches(String regex)判断字符串按照给定的regex(规则)是否正确。
public class StringTest4 {
    public static void main(String[] args) {
        String s="aa|bb|cc";
        //将此字符串按照给定的regex(规则)拆分为字符串数组
        String[] split = s.split("\\|");
        for (int i = 0; i <split.length ; i++) {
            System.out.print(split[i]);
        }

        System.out.println();
        //替换功能
        String s1="helloWorld";
        //替换字符
        String new_string = s1.replace('l', 'k');
        System.out.println(new_string);
        //替换字符串
        String new_string1=s1.replace("hello","hi");
        System.out.println(new_string1);

        //替换空格
        String s2="hello world";
        String s3 = s2.replaceAll("\\s", "!");
        System.out.println(s3);

        //去除首尾的空格
        String s4="  hello world ";
        String s5 = s4.trim();
        System.out.println(s5);

        //正则表达式-效验用户写到内容是否满足当前规定
        String s6="13638383838";
        boolean matches = s6.matches("^1[356789]\\d{9}$");
        System.out.println(matches);

    }
}

 

2.7、常量池

 

在学习String类型转换之前我们需要先了解一下StringBuilder、StringBuffer这两个类,因为String定义出来的字符串都是常量,是不能被改变的,而StringBuilder、StringBuffer这两个类是可以改变内容的,所以在类型转换中需要依靠这两个类来完成。

3、StringBuilder、StringBuffer类

StringBuilder、StringBuffer都是一个可变的字符串类,我们可以把它看成是一个容器,这里的可变指的是对象中的内容是可变的,也可称之为字符串缓冲类。StringBuilder和StringBuffer这两个类的方法功能是一样的,只是在线程中的安全性和效率不同,在下面会进行总结比较,下面的演示我以StringBuilder类为主。

3.1初始化StringBuilder类

        StringBuilder sb =new StringBuilder();
        System.out.println(sb);//
        System.out.println(sb.length());//0
        System.out.println(sb.capacity());//16

因为StringBuilder类可以看做是一个容器,所以直接输出对象的话是没有任何东西的。StringBuilder的默认内存存储量为16,也可以自己对存储值进行设置。需要在构造方法进行参数传递。

        StringBuilder sb2=new StringBuilder(4);
        System.out.println(sb2);//
        System.out.println(sb2.length());//0
        System.out.println(sb2.capacity());//4

如果在构造方法中传递的值为字符串形式,那么内存存储量为字符串长度+16。

        StringBuffer sb3=new StringBuffer("hello");
        System.out.println(sb3);//hello
        System.out.println(sb3.length());//5
        System.out.println(sb3.capacity());//21 16+5

3.2、append和insert添加方法

可以把任意类型数据添加到字符串缓冲区里面,并返回字符串缓冲区本身

public class Demo2 {
    public static void main(String[] args) {
        StringBuilder  sb=new StringBuilder();
        // sb.append("hello");
        // sb.append(4);
        // sb.append(true);
        // sb.append(false);
        // sb.append(6.3);
        //链式编程
        sb.append("hello").append(5).append(6.9).append(true).append(false);
        sb.insert(5,"ssl");//从5索引开始插入右边字符串中的内容
        System.out.println(sb);
    }
}

3.3、delete删除方法

public class Demo3 {
    public static void main(String[] args) {
        StringBuilder sb=new StringBuilder();
        //添加功能
        sb.append("hello").append("java").append("world");
        //删除功能
        //包左不包右
        sb.delete(5,9);
        //删除所有内容
        sb.delete(0,sb.length());
        System.out.println("sb:"+sb);
    }
}

3.4、replace替换方法

public class Demo4 {
    public static void main(String[] args) {
        //替换方法
        StringBuilder sb =new StringBuilder();
        sb.append("hello");
        sb.append("world");
        sb.append("java");
        System.out.println("sb:"+sb);
        sb.replace(5,10,"ssl");
        System.out.println("sb:"+sb);

    }
}

3.5、reverse反转方法

public class Demo5 {
    public static void main(String[] args) {
        StringBuilder sb =new StringBuilder();
        sb.append("国中爱我");
        sb.reverse();
        System.out.println("sb:"+sb);
    }
}

 

4、StringBuilder和String相互转换

1、StringBuilder转换为String

public String toString():通过 toString() 就可以实现把 StringBuilder 转换为String

2、String转换为StringBuilder

public StringBuilder(String s):通过构造方法就可以实现把 String 转换为 StringBuilder

public class Demo6 {
    public static void main(String[] args) {

        //StringBuilder和String的相互转换
        //String转换为StringBuilder 通过构造方法
        String s="hello";
        StringBuilder sb1=new StringBuilder(s);
        //通过append方法
        StringBuilder sb2=new StringBuilder();
        sb2.append(s);

        //StringBuilder转为String  toString方法
        String s1=sb1.toString();
        System.out.println(s1);

        String s2 = sb2.toString();
        System.out.println(s2);
        
        //String 构造方法
        String s3=new String(sb1);
        System.out.println(s3);

    }
}

 5、StringBuilder,StringBuffer和String区别

1、String是内容不可变的,而StringBuffer,StringBuilder都是内容可变的。

2、StringBuffer是同步的,数据安全,效率低。

3、StringBuilder是不同步的,数据不安全,效率高。

6、字符串拼接案例

 定义一个方法,把 int 数组中的数据按照指定的格式拼接成一个字符串返回,调用该方法, 并在控制台输出结果。
        例如,数组为int[] arr = {1,2,3}; ,执行方法后的输出结果为:[1, 2, 3] 

public class Demo1 {
    public static void main(String[] args) {
        //定义一个方法  把int数组中的数据按照指定的格式拼接成一个字符串返回
        int[] arr={1,6,8};
        String  s=intToString(arr);
        System.out.println(s);
    }

    private static String intToString(int[] arr) {
        StringBuilder sb =new StringBuilder();
        sb.append("[");
        for (int i = 0; i <arr.length ; i++) {
            if(i==arr.length-1){
                sb.append(arr[i]);
            }else{
                sb.append(arr[i]).append(",");
            }
        }
        sb.append("]");
        String s = sb.toString();
        return s;
    }

}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值