认识String类

一、常用方法

1.1 字符串构造

 public static void main(String[] args) {
        String str1 = new String("hi");//使用newString对象
        String str2 = "hello";//使用常量串构造

        //利用字符数组进行构造
        char[] ch = {'s','b','f'};
        String str3 = new String(ch);

        String str4 = str1;
        System.out.println(str1);
        System.out.println(str2);
        System.out.println(str3);
        System.out.println(str4);
    }

【注意】

1. String是引用类型,内部并不存储字符串本身

public static void main(String[] args) {
    // s1和s2引用的是不同对象 s1和s3引用的是同一对象
    String s1 = new String("hello");
    String s2 = new String("world");
    String s3 = s1;
    System.out.println(s1.length()); // 获取字符串长度---输出5
    System.out.println(s1.isEmpty()); // 如果字符串长度为0,返回true,否则返回false
}

2. 在Java中双引号“”引起来的也是String类型对象。

System.out.println("hello".length());

1.2 String对象的比较

1. ==比较是否引用同一个对象

对于内置类型: ==比较的是变量中的值

对于引用类型: ==比较的是引用中的地址

public static void main(String[] args) {
        String s1 = new String("hello");
        String s2 = new String("hello");
        String s3 = s1;
        String s4 = "Hello";

        //内置类型:== 比较的是变量的值
        //引用类型:== 比较的是引用中的地址
        System.out.println(s1 == s2);
        System.out.println(s1 == s3);
        System.out.println(s3 == s2);
    }

2. boolean equals(Object anObject) 方法:按照字典序比较

String类重写了父类Object中equals方法,Object中equals默认按照==比较,String重写equals方法后,按照 如下规则进行比较:

  1. 先检测this 和 anObject 是否为同一个对象比较,如果是返回true
  2. 检测anObject是否为String类型的对象,如果是继续比较,否则返回false
  3. this和anObject两个字符串的长度是否相同,是继续比较,否则返回false
  4. 按照字典序,从前往后逐个字符进行比较
public static void main(String[] args) {
        String s1 = new String("hello");
        String s2 = new String("hello");
        String s3 = s1;
        String s4 = "Hello";

        //equals比较的是对象里面的值
        System.out.println(s1.equals(s2));
        System.out.println(s1.equals(s3));
        System.out.println(s2.equals(s3));
}

3. int compareTo(String s) 方法: 按照字典序进行比较

compareTo返回的是int类型。具体比较方式:

1. 先按照字典次序大小比较,如果出现不等的字符,直接返回这两个字符的大小差值

2. 如果前k个字符相等(k为两个字符长度最小值),返回值两个字符串长度差值

public static void main(String[] args) {
        String s1 = new String("hello");
        String s2 = new String("hello");
        String s3 = s1;
        String s4 = "Hello";

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

4. int compareToIgnoreCase(String str) 方法:与compareTo方式相同,但是忽略大小写比较

public static void main(String[] args) {
        String s1 = new String("hello");
        String s2 = "Hello";

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

1.3 字符串查找 

方法功能
char charAt(int index)返回index位置上字符,如果index为负数或者越界,抛出 IndexOutOfBoundsException异常
int indexOf(int ch)返回ch第一次出现的位置,没有返回-1
int indexOf(int ch, int fromIndex)从fromIndex位置开始找ch第一次出现的位置,没有返回-1
int indexOf(String str)返回str第一次出现的位置,没有返回-1
int indexOf(String str, int fromIndex)从fromIndex位置开始找str第一次出现的位置,没有返回-1
int lastIndexOf(int ch)从后往前找,返回ch第一次出现的位置,没有返回-1
int lastIndexOf(int ch, int fromIndex)从fromIndex位置开始找,从后往前找ch第一次出现的位置,没有返 回-1
int lastIndexOf(String str)从后往前找,返回str第一次出现的位置,没有返回-1
int lastIndexOf(String str, int fromIndex)从fromIndex位置开始找,从后往前找str第一次出现的位置,没有返 回-1

public static void main(String[] args) {
        String s1 = new String("abcabcda");
        System.out.println(s1.charAt(1));//b
        System.out.println(s1.indexOf('c'));//2
        System.out.println(s1.indexOf('c',4));//5
        System.out.println(s1.indexOf("abc"));//0
        System.out.println(s1.indexOf("abc",3));//3
        System.out.println(s1.lastIndexOf('c'));//5
        System.out.println(s1.lastIndexOf('c',5));//5
        System.out.println(s1.lastIndexOf("bc"));//4
        System.out.println(s1.lastIndexOf("bc",2));//1
    }

1.4 转化

1. 数值和字符串转化

public static void main4(String[] args) {
        //数字转字符串
        String s1 = String.valueOf(123);
        String s2 = String.valueOf(12.3);
        String s3 = String.valueOf(true);
        String s4 = String.valueOf(new Student("hanmeimei",19,"女"));
        System.out.println(s1);
        System.out.println(s2);
        System.out.println(s3);
        System.out.println(s4);
        System.out.println("------");
        //字符串转数字
        int n1 = Integer.parseInt(s1);
        Double d1 = Double.parseDouble("12.23");
        System.out.println(s1 + " " + s2);
    }

2. 大小写转换

public static void main5(String[] args) {
        String s1 = new String("HelLo world");
        String s2 = "HeLLO Bit";
        String s3 = s1.toUpperCase();
        String s4 = s2.toLowerCase();
        System.out.println(s3);
        System.out.println(s4);
    }

3. 字符串转数组

public static void main(String[] args) {
    String s = "hello";
    // 字符串转数组
    char[] ch = s.toCharArray();
    for (int i = 0; i < ch.length; i++) {
        System.out.print(ch[i]);
    }
    System.out.println();
    // 数组转字符串
    String s2 = new String(ch);
    System.out.println(s2);
}

4. 格式化

public static void main5(String[] args) {
        String s = String.format("%d-%d-%d",2024,4,5);
        System.out.println(s);
    }

1.5 字符串替换 

使用一个指定的新的字符串替换掉已有的字符串数据,可用的方法如:

方法功能
String replaceAll(String regex, String replacement)替换所有的指定内容
String replaceFirst(String regex, String replacement)替换收个内容

public static void main6(String[] args) {
        String s1 = "good morning";
        String s2 = s1.replaceAll("o","r");
        String s3 = s1.replaceFirst("o","r");
        System.out.println(s2);
        System.out.println(s3);
    }

注意事项: 由于字符串是不可变对象, 替换不修改当前字符串, 而是产生一个新的字符串.


1.6 字符串拆分 split

可以将一个完整的字符串按照指定的分隔符划分为若干个子字符串。 可用方法如下:

方法功能
String[] split(String regex)将字符串全部拆分
String[] split(String regex, int limit)将字符串以指定的格式,拆分为limit组

public static void main7(String[] args) {
        //字符串的拆分
        String s = "nice to meet you bit";
        String[] s1 = s.split(" ");
        for (String str : s1) {
            System.out.println(str);
        }
        System.out.println("-----");
        String[] s2 = s.split(" ",3);
        for (String str : s2) {
            System.out.println(str );
        }
    }

有些特殊字符作为分割符可能无法正确切分, 需要加上转义

1. 字符"|","*","+"都得加上转义字符,前面加上 "\\" .

2. 而如果是 "\" ,那么就得写成 "\\\\" .

3. 如果一个字符串中有多个分隔符,可以用"|"作为连字符.

public static void main7(String[] args) {
        //1. 字符"|","*","+"都得加上转义字符,前面加上 "\\" .
        String s3 = "192.168.1.1";
        String[] s4 = s3.split("\\.");
        for(String str : s4){
            System.out.println(str);
        }
        //2. 而如果是 "\" ,那么就得写成 "\\\\" .
        String s5 = "ab\\cd\\ef";
        String[] s6 = s5.split("\\\\");
        for(String str : s6){
            System.out.println(str);
        }
        //3. 如果一个字符串中有多个分隔符,可以用"|"作为连字符.
        String s7 = "sas\\fjsio&dsf";
        String[] s8 = s7.split("\\\\|&");
        for (String str : s8) {
            System.out.println(str);
        }
    }

1.7 字符串截取 subString

从一个完整的字符串之中截取出部分内容。可用方法如下:

方法功能
String substring(int beginIndex)从指定索引截取到结尾
String substring(int beginIndex, int endIndex)截取部分内容

1. 索引从0开始

2. 注意前闭后开区间的写法, substring(0, 5) 表示包含 0 号下标的字符, 不包含 5 号下标

String str = "helloworld" ;
System.out.println(str.substring(5));
System.out.println(str.substring(0, 5));

1.8 其他造作方法

方法功能
String trim()去掉字符串中的左右空格,保留中间空格
String toUpperCase()字符串转大写
String toLowerCase()字符串转小写

trim 会去掉字符串开头和结尾的空白字符(空格, 换行, 制表符等)

String str = " hello world " ;
System.out.println("["+str+"]");
System.out.println("["+str.trim()+"]");

1.9 字符串的不可变性

String是一种不可变对象. 字符串中的内容是不可改变。字符串不可被修改,是因为:

1. String类在设计时就是不可改变的,String类实现描述中已经说明了String类中的字符实际保存在内部维护的value字符数组中。

String类被final修饰,表明该类不能被继承

value被修饰被final修饰,表明value自身的值不能改变,即不能引用其它字符数组,但是其引用空间中 的内容可以修改。

2. 所有涉及到可能修改字符串内容的操作都是创建一个新对象,改变的是新对象

final修饰类表明该类不想被继承,final修饰引用类型表明该引用变量不能引用其他对象,但是其引用对象中的内 容是可以修改的。

1.10 字符串修改

注意:尽量避免直接对String类型对象进行修改,因为String类是不能修改的,所有的修改都会创建新对象,效率 非常低下。但是这种方式不推荐使用,因为其效率非常低,中间创建了好多临时对象

public static void main(String[] args) {
        long start = System.currentTimeMillis();
        String s = "";
        for (int i = 0; i < 10000; ++i) {
            s += i;
        }
        long end = System.currentTimeMillis();
        System.out.println(end - start);//111

        start = System.currentTimeMillis();
        StringBuffer sbf = new StringBuffer("");
        for (int i = 0; i < 10000; ++i) {
            sbf.append(i);
        }
        end = System.currentTimeMillis();
        System.out.println(end - start);//0

        start = System.currentTimeMillis();
        StringBuilder sbd = new StringBuilder("");
        for (int i = 0; i < 10000; ++i) {
            sbd.append(i);
        }
        end = System.currentTimeMillis();
        System.out.println(end - start);//0
    }

可以看出在对String类进行修改时,效率是非常慢的,因此:尽量避免对String的直接需要,如果要修改建议尽量 使用StringBuffer或者StringBuilder。

二、StringBuilder和StringBuffer

 StringBuilder的介绍

由于String的不可更改特性,为了方便字符串的修改,Java中又提供StringBuilder和StringBuffer类。这两个类大 部分功能是相同的,这里介绍 StringBuilder常用的一些方法

方法功能
StringBuff append(String str)在尾部追加,相当于String的+=,可以追加:boolean、char、char[]、 double、float、int、long、Object、String、StringBuff的变量
char charAt(int index)获取index位置的字符
int length()获取字符串的长度
int capacity()获取底层保存字符串空间总的大小
void ensureCapacity(int mininmumCapacity)扩容
void setCharAt(int index, char ch)将index位置的字符设置为ch
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最后一次出现的位置
StringBuff insert(int offset, String str)在offset位置插入:八种基类类型 & String类型 & Object类型数据
StringBuffer deleteCharAt(int index)删除index位置字符
StringBuffer delete(int start, int end)删除[start, end)区间内的字符
StringBuffer replace(int start, int end, String str)将[start, end)位置的字符替换为str
String substring(int start)从start开始一直到末尾的字符以String的方式返回
String substring(int start,int end)将[start, end)范围内的字符以String的方式返回
StringBuffer reverse()反转字符串
String toString()将所有字符按照String的方式返回
public static void main(String[] args) {
            StringBuilder sbd1 = new StringBuilder("hello");
            StringBuilder sbd2 = sbd1;
        System.out.println(sbd1.append(' '));//hello 
        System.out.println(sbd1.append("world"));//hello world
        System.out.println(sbd1.append("123"));//hello world123
        System.out.println(sbd1 == sbd2);//true
        System.out.println(sbd1.charAt(1));//e
        System.out.println(sbd1.length());//14
        System.out.println(sbd1.capacity());//获取底层保存字符串空间总的大小 21
        sbd1.setCharAt(0,'H');
        System.out.println(sbd1);//Hello world123
        System.out.println(sbd1.insert(1, "[Hello word!!!]"));//H[Hello word!!!]ello world123
        System.out.println(sbd1.indexOf("Hello"));//2
        System.out.println(sbd1.lastIndexOf("Hello"));//2
        System.out.println(sbd1.deleteCharAt(0));//[Hello word!!!]ello world123
        System.out.println(sbd1.delete(0, 5));//[0,5)  o word!!!]ello world123

        String str = sbd1.substring(0,5);
        System.out.println(str);//o wor

        System.out.println(sbd1.reverse());//321dlrow olle]!!!drow o

        str = sbd1.toString();
        System.out.println(str);//321dlrow olle]!!!drow o
    }

从上述例子可以看出:String和StringBuilder最大的区别在于String的内容无法修改,而StringBuilder的内容可 以修改。频繁修改字符串的情况考虑使用StringBuilder。

注意:

String和StringBuilder类不能直接转换。如果要想互相转换,可以采用如下原则:

String变为StringBuilder: 利用StringBuilder的构造方法或append()方法

StringBuilder变为String: 调用toString()方法

  • 17
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值