锋盈数科-知识库 Logo
首页
软件开发
计算机基础
Hello Halo
新手必读
关于本知识库
登录 →
锋盈数科-知识库 Logo
首页 软件开发 计算机基础 Hello Halo 新手必读 关于本知识库
登录
  1. 首页
  2. 软件开发
  3. JavaSE——String类常用方法详解(玩转字符串)

JavaSE——String类常用方法详解(玩转字符串)

0
  • 软件开发
  • 发布于 2024-09-19
  • 0 次阅读
黄健
黄健

作者:敲代码の流川枫

博客主页:流川枫的博客

专栏:和我一起学java

语录:Stay hungry stay foolish

工欲善其事必先利其器,给大家介绍一款超牛的斩获大厂offer利器——牛客网

点击免费注册和我一起刷题吧

文章目录

1. 字符串的常用构造

2. String对象的比较

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

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

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

4. int compareToIgnoreCase(String str)方法

3. 字符串查找

char charAt(int index)

int indexOf(int ch)

int indexOf(int ch, int fromIndex)

int indexOf(String str)

int indexOf(String str, int fromIndex)

int lastIndexOf(int ch)

int lastIndexOf(int ch, int fromIndex)

int lastIndexOf(String str)

int lastIndexOf(String str, int fromIndex)

4. 转化

1. 数值和字符串转化

2. 大小写转换

3. 字符串转数组

4. 格式化

5. 字符串替换

1.替换所有的指定内容

2.替换首个内容

6. 字符串拆分

1.字符串全部拆分

2.字符串以指定的格式,拆分为limit组

3. “.“分割

7. 字符串截取

1.从指定索引截取到结尾

2.截取部分内容

8. String trim()



  1. 字符串的常用构造

1.使用常量构造

2.使用newString构造

3.使用字符数组构造

public class Test {
    public static void main(String[] args) {
        //1
        String str1 = "hello";
        System.out.println(str1);
        //2
        String str2 = new String("hello");
        System.out.println(str2);
        //3
        char[] chars = {'h','e','l','l','o'};
        System.out.println(chars);
    }
}

其它方法使用时参考:字符串官方文档

字符串是不能被继承的,下面是String类源码

value是一个char类型数组,字符串实际存储在char类型的数组中,且字符串结尾没有/0

因此String是引用类型,内部并不存储字符串本身,看一个例子:

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

        String str1 = new String("hello");

        String str2 = new String("world");

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

str1和str2引用的是不同对象str1和str3引用的是同一对象

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

        String str1 = new String("hello");

        String str2 = new String("hello");

        System.out.println(str1==str2);

        System.out.println(str1.equals(str2));

    }
}

因为String类是引用类型,所以就算字符串内容一样,它们也不相等,要想比较它们是否相等,要通过对象调用方法来比较

在Java中,““引起来的也是String类的对象

public class Test {
    public static void main(String[] args) {
        System.out.println("hello".toString());

    }
}

可以调用toString()等方法

  1. String对象的比较

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

对于基本类型变量,比较的是两个变量中存储的值是否相同

对于引用类型变量,比较的是两个引用变量引用的是否为同一个对象

如上文提到的

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

字典序:字符大小的顺序

String类重写了父类Object中equals方法,Object中equals默认按照==比较

重写之后的比较逻辑:

 public boolean equals(Object anObject) {

        //1. 先检测this和anObject是否为同一个对象比较,如果是返回true

        if (this == anObject) {
            return true;
        }

        //2. 检测anObject是否为String类型的对象,如果是继续比较,否则返回false

        if (anObject instanceof 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;
    }

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

equals返回的是boolean类型,而compareTo返回的是int类型

比较方式:

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

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

看一个例子:

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

        String str1 = new String("hello");

        String str2 = new String("hello");

        int ret = str1.compareTo(str2);
        if(ret>0){
            System.out.println("str1>str2");
        } else if (ret==0) {
            System.out.println("str1=str2");
        }
        else {
            System.out.println("str1<str2");
        }

    }

}

源码:

public int compareTo(String anotherString) {
        int len1 = value.length;
        int len2 = anotherString.value.length;
        int lim = Math.min(len1, len2);
        char v1[] = value;
        char v2[] = anotherString.value;

        int k = 0;
        while (k < lim) {
            char c1 = v1[k];
            char c2 = v2[k];
            if (c1 != c2) {
                return c1 - c2;
            }
            k++;
        }
        return len1 - len2;
    }

4. int compareToIgnoreCase(String str)方法

与compareTo方式相同,但是忽略大小写比较

public class Test {
    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

    }
}

  1. 字符串查找

String类提供的常用查找的方法:

char charAt(int index)

返回index位置上字符,如果index为负数或者越界,抛出IndexOutOfBoundsException异常

public class Test {
    public static void main(String[] args) {
        String s1 = new String("abcdef");
        for (int i= 0;  i< s1.length(); i++) {
            System.out.println(s1.charAt(i));
        }
    }
}

int indexOf(int ch)

返回ch第一次出现的位置,没有返回-1

public class Test {
    public static void main(String[] args) {
        String s1 = new String("abcdef");

        System.out.println(s1.indexOf('c'));
    }
}

int indexOf(int ch, int fromIndex)

从fromIndex位置开始找ch第一次出现的位置,没有返回-1

public class Test {
    public static void main(String[] args) {
        String s1 = new String("abcdecf");

        System.out.println(s1.indexOf('c',3));
    }
}

int indexOf(String str)

返回str第一次出现的位置,没有返回-1

public class Test {
    public static void main(String[] args) {
        String s1 = new String("abcdecf");

        System.out.println(s1.indexOf("cde"));
    }
}

int indexOf(String str, int fromIndex)

从fromIndex位置开始找str第一次出现的位置,没有返回-1

public class Test {
    public static void main(String[] args) {
        String s1 = new String("abcdecf");

        System.out.println(s1.indexOf("cde",3));
    }
}

int lastIndexOf(int ch)

从后往前找,返回ch第一次出现的位置,没有返回-1

public class Test {
    public static void main(String[] args) {
        String s1 = new String("abcdecf");

        System.out.println(s1.lastIndexOf("c"));
    }
}

int lastIndexOf(int ch, int fromIndex)

从fromIndex位置开始找,从后往前找ch第一次出现的位置,没有返回-1

public class Test {
    public static void main(String[] args) {
        String s1 = new String("abcdecf");

        System.out.println(s1.lastIndexOf("c",4));
    }
}

int lastIndexOf(String str)

从后往前找,返回str第一次出现的位置,没有返回-1

public class Test {
    public static void main(String[] args) {
        String s1 = new String("abcdecf");

        System.out.println(s1.lastIndexOf("abc"));
    }
}

int lastIndexOf(String str, int fromIndex)

从fromIndex位置开始找,从后往前找str第一次出现的位置,没有返回-1

public class Test {
    public static void main(String[] args) {
        String s1 = new String("abcdecf");

        System.out.println(s1.lastIndexOf("abc",4));
    }
}

  1. 转化

1. 数值和字符串转化

public class Test {
    public static void main(String[] args) {
        String s1 = String.valueOf(123);

        System.out.println(s1);
    }
}

可以看到有很多重载的方法供我们使用,可以将很多不同类型的数值转换为字符串

2. 大小写转换

toUpperCase()

toLowerCase()

public class Test {
    public static void main(String[] args) {
        String s1 = "hellO嗨";
        String ret = s1.toUpperCase();
        System.out.println(ret);
    }
}

toUpperCase() 只会将小写转换成大写,其它都不变,toLowerCase()也是如此

3. 字符串转数组

toCharArray()

public class Test {
    public static void main(String[] args) {
        String str1 = "abcdef";
        char[] chars = str1.toCharArray();
        System.out.println(Arrays.toString(chars));
    }
}

数组转字符串

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

        char[] chars = {'h','e','l','l','o'};
        String s1 = new String(chars);
        System.out.println(s1);
    }
}

4. 格式化

String.format()

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

        String s = String.format("%d-%d-%d",2022,8,14);
        System.out.println(s);
    }
}

  1. 字符串替换

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

使用一个的字符串替换已有的字符串数据,方法:

1.String replaceAll(String regex, String replacement)

2.String replaceFirst(String regex, String replacement)

1.替换所有的指定内容

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

        String s = "abcadeafagf";
        String ret = s.replaceAll("a","c");
        System.out.println(s);
        System.out.println(ret);
    }
}

可以看出替换字符串后原字符串是不变的,替换后需要一个新的字符串接收

2.替换首个内容

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

        String s = "abcadeafagf";
        String ret = s.replaceFirst("a","c");
        System.out.println(s);
        System.out.println(ret);
    }
}

  1. 字符串拆分

将一个完整的字符串按照指定的分隔符划分为若干个子字符串

String[] split(String regex)

String[] split(String regex, int limit)

1.字符串全部拆分

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

        String s = "hello world hello";
        String[] ret = s.split(" ");
        System.out.println(s);
        System.out.println(Arrays.toString(ret));
    }
}

2.字符串以指定的格式,拆分为limit组

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

        String s = "hello world hello";
        String[] ret = s.split(" ",2);
        System.out.println(s);
        System.out.println(Arrays.toString(ret));
    }
}

3. “.“分割

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

        String s = "hello.world.hello";
        String[] ret = s.split(".");
        System.out.println(s);
        System.out.println(Arrays.toString(ret));
    }
}

正常使用split(“.“)进行分割,我们发现打印数组是空的,说明没有分割成功

原因:“.“需要转义,添加”\\.“后,可以分割

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

        String s = "hello.world.hello";
        String[] ret = s.split("\\.");
        System.out.println(s);
        System.out.println(Arrays.toString(ret));
    }
}

总结:

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

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

  3. 如果一个字符串中有多个分隔符,可以用”\|“作为连字符,即s.split(“=\|\&“);是通过=和\&分割s字符串

  1. 字符串截取

String substring(int beginIndex)

String substring(int beginIndex, int endIndex)

1.从指定索引截取到结尾

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

        String s = "hello world";
        String ret = s.substring(5);
        System.out.println(s);
        System.out.println(ret);
    }
}

2.截取部分内容

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

        String s = "hello world";
        String ret = s.substring(0,5);
        System.out.println(s);
        System.out.println(ret);
    }
}

总结:

  1. 索引从0开始

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

  1. String trim()

功能:去掉字符串中的左右空格,保留中间空格

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

        String s = "   hello world    ";
        String ret = s.trim();
        System.out.println(s);
        System.out.println(ret);
    }
}

总结:

我们注意到,大多数的String类方法都不是直接操作原字符串,都会返回一个新的字符串
” 本期的分享就到这里了, 记得给博主一个三连哈,你的支持是我创作的最大动力!

原文链接: https://blog.csdn.net/chenchenchencl/article/details/126330055

标签: #JAVA 991 #软件开发 1171
相关文章

万字:支付“核心系统”详解 2024-11-02 15:33

专栏作者:隐墨星辰 \| 主编:陈天宇宙 这篇文章也尝试化繁为简,探寻支付系统的本质,讲清楚在线支付系统最核心的一些概念和设计理念。 虽然支付行业已经过了风头最劲的时光,但跨境支付仍然在蓬勃发展,每年依然有很多新人进入这个行业,这篇文章尝试为这些刚入行的新人提供一点帮助。 文章只介绍一些支付行业十几

资深支付架构师视角:实战从问题定义到代码落地的完整套路 2024-11-02 15:33

前言 今天从一个实际案例入手,介绍站在架构师的角度,如何识别并定义问题,提炼需求,技术方案选型,再到详细设计,最后利用AI的能力协助写出核心的代码,验证与调优。 解决问题存在一定的模式,也可以称之为框架,总结出自己的思考和解题框架,以后再碰到同类型的问题就可以如庖丁解牛一样容易。 很多年前,我写代码

Spring 实现 3 种异步接口 2024-10-18 09:07

大家好,我是苏三~ 如何处理比较耗时的接口? 这题我熟,直接上异步接口,使用 Callable、WebAsyncTask 和 DeferredResult、CompletableFuture等均可实现。 但这些方法有局限性,处理结果仅返回单个值。在某些场景下,如果需要接口异步处理的同时,还持续不断地

重学SpringBoot3-集成Redis(五)之布隆过滤器 2024-10-08 11:24

更多SpringBoot3内容请关注我的专栏:《SpringBoot3》 期待您的点赞👍收藏⭐评论✍ 重学SpringBoot3-集成Redis(五)之布隆过滤器 1. 什么是布隆过滤器? * 基本概念 适用场景 2. 使用 Redis 实现布隆过滤器 * 项目依赖 Redis 配置

设计模式第16讲——迭代器模式(Iterator) 2024-10-08 11:24

一、什么是迭代器模式 迭代器模式是一种行为型设计模式,它提供了一种统一的方式来访问集合对象中的元素,而不是暴露集合内部的表示方式。简单地说,就是将遍历集合的责任封装到一个单独的对象中,我们可以按照特定的方式访问集合中的元素。 二、角色组成 抽象迭代器(Iterator):定义了遍历聚合对象所需的方法

vue2路由和vue3路由区别及原理 2024-10-08 11:24

一、Vue2 与 Vue3 路由的区别 1. 创建路由实例方式的不同 Vue 2 中,通过 Vue.use() 注册路由插件,并通过 new VueRouter() 来创建路由实例。 import Vue from 'vue';import VueRouter from 'vue-router';i

目录

IT 外包服务商

  • 意见投递
  • zyf6619

软件开发应用

主菜单

  • 首页
  • 软件开发
  • 计算机基础
  • Hello Halo
  • 新手必读
  • 关于本知识库
Copyright © 2024 your company All Rights Reserved. Powered by Halo.