Java中的String类

1. String类的重要性

在C语言中已经涉及到字符串了,但是在C语言中要表示字符串只能使用字符数组或者字符指针,可以使用标准库提供的字符串系列函数完成大部分操作,但是这种将数据和操作数据方法分离开的方式不符合面相对象的思想,而字符串应用又非常广泛,因此Java语言专门提供了String类。

2. 常用方法

2.1 字符串构造

String类提供的构造方式非常多,常用的就以下三种:

public static void main(String[] args) {
 // 使用常量串构造
String s1 = "hello world";
 System.out.println(s1);
 // 直接newString对象
String s2 = new String("hello world");
 System.out.println(s1);
 // 使用字符数组进行构造
char[] array = {'h','e','l','l','o','w','o','r','l','d'};
 String s3 = new String(array);
 System.out.println(s1);
 }

在这里插入图片描述

在这里插入图片描述

其他方法需要用到时,大家参考Java在线文档:String官方文档


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;
 }

在这里插入图片描述
2.在Java中“”引起来的也是String类型对象

public static void main(String[] args) {
        System.out.println("hello".length());
    }

在这里插入图片描述

2.2 String对象的比较

字符串的比较是常见操作之一,比如:字符串排序。Java中总共提供了4中方式:
1. ==比较是否引用同一个对象

注意: 对于内置类型,== 比较的是变量中的值;对于引用类型 == 比较的是引用中的地址
在这里插入图片描述

2. boolean equals(Object anObject)方法:按照字典序比较
字典序:字符大小的顺序
String类重写了父类Object中equals方法,Object中equals默认按照==比较,String重写equals方法后,按照如下规则进行比较,比如:

public boolean equals(Object anObject) {
    // 1. 先检测this 和 anObject 是否为同一个对象比较,如果是返回true
    if (this == anObject) {
        return true;
    }
    
    // 2. 检测anObject是否为String类型的对象,如果是继续比较,否则返回false
    if (anObject instanceof String) {
        // 将anObject向下转型为String类型对象
        String anotherString = (String)anObject;
        int n = value.length;
        
        // 3. this和anObject两个字符串的长度是否相同,是继续比较,否则返回false
        if (n == anotherString.value.length) {
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = 0;
            
            // 4. 按照字典序,从前往后逐个字符进行比较
            while (n-- != 0) {
                if (v1[i] != v2[i])
                    return false;
                i++;
            }
            return true;
        }
    }
    return false;
 }
 public static void main(String[] args) {
    String s1 = new String("hello");
    String s2 = new String("hello");
    String s3 = new String("Hello");
 
    // s1、s2、s3引用的是三个不同对象,因此==比较结果全部为false
    System.out.println(s1 == s2);       // false
    System.out.println(s1 == s3);       // false
 
    // equals比较:String对象中的逐个字符
    // 虽然s1与s2引用的不是同一个对象,但是两个对象中放置的内容相同,因此输出true
    // s1与s3引用的不是同一个对象,而且两个对象中内容也不同,因此输出false
    System.out.println(s1.equals(s2));  // true
    System.out.println(s1.equals(s3));  // false
 }

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

与equals不同的是,equals返回的是boolean类型,而compareTo返回的是int类型。具体比较方式:
1.先按照字典次序大小比较,如果出现不等的字符,直接返回这两个字符的大小差值
2. 如果前k个字符相等(k为两个字符长度最小值),返回值两个字符串长度差值

public static void main(String[] args) {
    String s1 = new String("abc");
    String s2 = new String("ac");
    String s3 = new String("abc");
    String s4 = new String("abcdef");
    System.out.println(s1.compareTo(s2));   // 不同输出字符差值-1
    System.out.println(s1.compareTo(s3));   // 相同输出 0
    System.out.println(s1.compareTo(s4));   // 前k个字符完全相同,输出长度差值 -3
 }

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

public static void main(String[] args) {
    String s1 = new String("abc");
    String s2 = new String("ac");
    String s3 = new String("ABc");
    String s4 = new String("abcdef");
    System.out.println(s1.compareToIgnoreCase(s2));   // 不同输出字符差值-1
    System.out.println(s1.compareToIgnoreCase(s3));   // 相同输出 0
    System.out.println(s1.compareToIgnoreCase(s4));   // 前k个字符完全相同,输出长度差值 -3
 }

2.3 字符串查找

字符串查找也是字符串中非常常见的操作,String类提供的常用查找的方法:

方法功能
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

2.4 转化

  1. 数值和字符串转化
public static void main(String[] args) {
    // 数字转字符串
    String s1 = String.valueOf(1234);
    String s2 = String.valueOf(12.34);
    String s3 = String.valueOf(true);
    String s4 = String.valueOf(new Student("Hanmeimei", 18));
    System.out.println(s1);
    System.out.println(s2);
    System.out.println(s3);
    System.out.println(s4);
    System.out.println("=================================");
    // 字符串转数字
    int data1 = Integer.parseInt("1234");
    double data2 = Double.parseDouble("12.34");
    System.out.println(data1);
    System.out.println(data2);
 }
  1. 大小写转换
public static void main(String[] args) {
    String s1 = "hello";
    String s2 = "HELLO";
    // 小写转大写
    System.out.println(s1.toUpperCase());
    // 大写转小写
    System.out.println(s2.toLowerCase());
}
  1. 字符串转数组
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);
}
  1. 格式化
public static void main(String[] args) {
    String s = String.format("%d-%d-%d", 1949,10,1);
    System.out.println(s);
}

2.5 字符串替换

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

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

代码示例: 字符串的替换处理

public static void main(String[] args) {
        String str = "helloworld" ;
        System.out.println(str.replaceAll("l", "_"));
        System.out.println(str.replaceFirst("l", "_"));
}

在这里插入图片描述
由于字符串是不可变对象, 替换不修改当前字符串, 而是产生一个新的字符串.

2.6 字符串拆分

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

方法功能
String[] split(String regex)将字符串全部拆分
String[] split(String regex, int limit)将字符串以指定的格式,拆分为limit组
2.6.1字符串的拆分处理:
public static void main(String[] args) {
    String str = "hello world hello bit" ;
    String[] result = str.split(" ") ; // 按照空格拆分
    for(String s: result) {
        System.out.println(s);
    }
}

在这里插入图片描述

2.6.2字符串的部分拆分:
public static void main(String[] args) {
    String str = "hello world hello 鱼嘟嘟" ;
    String[] result = str.split(" ",3) ;
    for(String s: result) {
        System.out.println(s);
    }
}

在这里插入图片描述

拆分是特别常用的操作. 一定要重点掌握. 另外有些特殊字符作为分割符可能无法正确切分, 需要加上转义.

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

2.6.3拆分IP地址:
public static void main(String[] args) {
    String str = "192.168.1.1" ;
    String[] result = str.split("\\.") ;
    for(String s: result) {
        System.out.println(s);
    }
}

在这里插入图片描述
在这里插入图片描述

2. 而如果是" \ “(转义字符表示为“\ \ ”),那么就得写成” \ \ \ \ ".

public static void main(String[] args) {
    String str = "鱼嘟嘟\\萝嘟嘟\\小小彬\\幸福一家人" ;
    String[] result = str.split("\\\\") ;
    for(String s: result) {
        System.out.println(s);
    }
}

在这里插入图片描述

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

public static void main(String[] args) {
   String str="zhangsan&lisi@wangwu";
   String[] ret=str.split("&|@");
    for (int i = 0; i < ret.length; i++) {
        System.out.println(ret[i]);
    }
}

在这里插入图片描述

2.7 字符串截取

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

方法功能
String substring(int beginIndex)从指定索引截取到结尾
String substring(int beginIndex, int endIndex)截取部分内容
public static void main(String[] args) {
   String str="zhangsanlovelisi";
    System.out.println(str.substring(1));//从指定索引截取到结尾
    System.out.println(str.substring(0, 5));//注意前闭后开区间的写法, substring(0, 5) 表示包含 0 号下标的字符, 不包含 5 号下标
}

在这里插入图片描述
注意前闭后开区间的写法, substring(0, 5) 表示包含 0 号下标的字符, 不包含 5 号下标

2.8 trim()方法

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

观察trim()方法的使用:

public static void main(String[] args) {
    String str = "   hello  world   " ;
    System.out.println("["+str+"]");
    System.out.println("["+str.trim()+"]");
}

在这里插入图片描述

2.9 字符串的不可变性

上面我们介绍了许多对字符串的修改的方法,但是又为何说字符串是不可变的呢??
前面我们学习过final修饰一个类表示当前类不能被继承
被final修饰的数组比如:final array[]={1,2,3,4};表示的也只是当前的引用指向的对象不可变,并不是对象的内容不可改变,那么字符串的不可变性是为什么呢?
我们看一下String类的源码,就一目了然了
在这里插入图片描述
那么又引发了一个新的问题,平常我们修改了之后也修改成功了,那是因为本质上,
所有字符串的修改操作是先创建了一个新的对象,改变的是新对象,原本的字符串变量并没有被修改。

在这里插入图片描述
错误说法:网上有些人说:字符串不可变是因为其内部保存字符的数组被final修饰了,因此不能改变。
这种说法是错误的,不是因为String类自身,或者其内部value被final修饰而不能被修改。

为什么 String 要设计成不可变的?(不可变对象的好处是什么?)

  1. 方便实现字符串对象池. 如果 String 可变, 那么对象池就需要考虑写时拷贝的问题了.
  2. 不可变对象是线程安全的.
  3. 不可变对象更方便缓存 hash code, 作为 key 时可以更高效的保存到 HashMap 中

2.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);
        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);
        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);
    }

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

3. StringBuilder和StringBuffer

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

3.1 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的方式返回

其中常见的方法使用如下:

3.1.1 StringBuff append(String str)

在这里插入图片描述

在这里插入图片描述

3.1.2StringBuff insert(int offset, String str)

在这里插入图片描述

在这里插入图片描述

3.2 String、StringBuffer、StringBuilder的区别

  • String的内容不可修改,StringBuffer与StringBuilder的内容可以修改.
  • StringBuffer与StringBuilder大部分功能是相似的
  • StringBuffer采用同步处理,属于线程安全操作;而StringBuilder未采用同步处理,属于线程不安全操 作
    在这里插入图片描述
    其中synchronized表示多线程情况下使用
  • 8
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值