Java字符串操作全解析

目录

一、字符串的创建

1.直接赋值型

2.通过new创建对象

3.通过字符数组创建

二、常用的String方法

1.获取字符串的长度

2.equals()比较字符串内容是否相等

3.compareTo比较字符串大小

4.通过索引寻找字符串的某个字符

5.通过字符串中的某个字符返回这个字符第一次出现位置

6.大小写的转换

7.字符串转数组

8.字符串替换

9.字符串的拆分

10.去除左右空格

11.字符串截取

下面两个为String类方法

1.数字转字符串

2.格式化字符串

三、StringBuilder类

1.字符串的修改

2.获取底层保存字符串空间总的大小与扩容

3.通过索引位置修改字符串

4.插入

5.删除

6.替换

7.逆转


一、字符串的创建

1.直接赋值型

java 复制代码
String s1 = "hello";

2.通过new创建对象

java 复制代码
String s2 = new String("abcd");

3.通过字符数组创建

java 复制代码
char[] chars = {'h','e','l','l','o'};
String s3 = new String(chars);

二、常用的String方法

1.获取字符串的长度

java 复制代码
String s1 = new String("ABCD");
System.out.println(s1.length());

2.equals()比较字符串内容是否相等

java 复制代码
public class Test1 {
    public static void main(String[] args) {
        String s1 = new String("abcd");
        String s2 = new String("abcd");
        System.out.println(s1.equals(s2)); //true
        System.out.println(s1==s2); //false
    }
}

上面例子中s1和s2的地址不同,所以s1==s2的结果是false,而equals()比较的是字符串的内容,所以结果为true。

java 复制代码
public class Test1 {
    public static void main(String[] args) {
        String s3 = "abcd";  // 常量池
        String s4 = "abcd";  // 复用常量池中的对象

        System.out.println(s3 == s4);      // true(同一对象)
        System.out.println(s3.equals(s4)); // true(内容相同)
    }
}

这个例子中的s3存储在常数池中,由于s4的内容与s3相同,直接复用s3的内容,s3与s4为同一个对象并且内容相同,故s3==s4与equals()的结果都是true。

3.compareTo比较字符串大小

java 复制代码
public class Test1 {
    public static void main(String[] args) {
        String s1 = "abcd";
        String s2 = "bcdf";
        System.out.println(s1.compareTo(s2));
    }
}

equals与compareTo都有忽略大小写比较的方法

java 复制代码
public class Test1 {
    public static void main(String[] args) {
        String s1 = new String("ABCD");
        String s2 = new String("abcd");
        System.out.println(s1.equalsIgnoreCase(s2));
        System.out.println(s1.compareToIgnoreCase(s2));
    }
}

4.通过索引寻找字符串的某个字符

java 复制代码
public class Test1 {
    public static void main(String[] args) {
        String s = "abcdefgh";
        char word = s.charAt(3);
        System.out.println(word);
    }
}

通过上面的方法我们可以通过索引遍历整个字符串

java 复制代码
public class Test1 {
    public static void main(String[] args) {
        String s = "abcdefgh";
        for (int i = 0; i < s.length(); i++) {
            char word = s.charAt(i);
            System.out.print(word);
        }
    }
}

5.通过字符串中的某个字符返回这个字符第一次出现位置

java 复制代码
public class Test1 {
    public static void main(String[] args) {
        String s = "abacddfegfhg";
        //返回字符d第一次出现位置
        System.out.println(s.indexOf('d'));
        //从索引2位置开始,返回d第一次出现的位置
        System.out.println(s.indexOf(2,'d'));
        //从9位置往前,返回第一个d出现的位置
        System.out.println(s.lastIndexOf('d', 9));
    }
}

6.大小写的转换

java 复制代码
public class Test1 {
    public static void main(String[] args) {
        String s1 = "abcd";
        String s2 = "ABCD";
        System.out.println(s1.toUpperCase());
        System.out.println(s2.toLowerCase());
    }
}

7.字符串转数组

java 复制代码
String s1 ="hello";
char[] chars = s1.toCharArray();
for(char ch:chars){
    System.out.print(ch+" ");
}

8.字符串替换

java 复制代码
String s = "qwefsdffgaaa";
String s1 = s.replace('a','b');
String s2 =s.replace("aa","kk");
String s3 = s.replaceFirst("a","3");
System.out.println(s1); //qwefsdffgbbb
System.out.println(s2); //qwefsdffgkka
System.out.println(s3); //qwefsdffg3aa

9.字符串的拆分

java 复制代码
    public static void main(String[] args) {
        String s = "zhangsan&wangwu";
        String[] rets = s.split("&");
        for(String x:rets){
            System.out.println(x);
        }
    }

10.去除左右空格

java 复制代码
    public static void main(String[] args) {
        String s ="     asdfg   gdrff  ";
        String ret = s.trim();
        System.out.println(ret);
    }

11.字符串截取

java 复制代码
    public static void main(String[] args) {
        String s ="helloworld";
        String s1 = s.substring(4,6);
        System.out.println(s1);
    }

下面两个为String类方法

1.数字转字符串

java 复制代码
    public static void main(String[] args) {
        String s1 = String.valueOf(1234);
        String s2 = String.valueOf(12.34);
        String s3 = String.valueOf(true);
        System.out.println(s1);
        System.out.println(s2);
        System.out.println(s3);
    }

2.格式化字符串

java 复制代码
    public static void main9(String[] args) {
        String s = String.format("%d-%d-%d",2019,9,12);
        System.out.println(s);
    }

创建一个直接赋值的字符串,它被存储到常量池中,再使用new创建一个字符串,使用 **intern()**可以将这个字符串加入常量池中,如果常量池已有这个字符串直接返回池中引用。
好处:节省内存;避免了重复创建字符串

java 复制代码
    public static void main1(String[] args) {
        //hello是字面值常量,本身就在常量池中
        String s1 = "hello";
        char[] chars = {'h','e','l','l','o'};
        String s2 = new String(chars);
        //当你觉得你的代码中,某个字符串经常用到,就可以主动加入池子中
        s2=s2.intern();
        System.out.println(s1==s2);
    }

在Java中String无法修改,若我们要修改字符串,则会创建新的字符串对象。为了方便修改字符串,Java又提供了StringBuilder和StringBuffer类,它们大部分内容相同,这里提供了一些常用的方法

三、StringBuilder类

1.字符串的修改

java 复制代码
    public static void main(String[] args) {
        StringBuilder stringBuilder = new StringBuilder("Hello");
        stringBuilder.append("World");
        System.out.println(stringBuilder); //HelloWorld
    }

对比String的每次修改字符串就重新创建新对象,当我们通过循环一个很大的数去修改字符串时,发现StringBulider的效率远大于String

java 复制代码
    public static void main(String[] args) {
        String s = "";
        int count = 100000;
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < count; i++) {
            s+=i;
        }
        long endTime = System.currentTimeMillis();
        System.out.println(endTime-startTime);  //2101
    }
java 复制代码
   public static void main4(String[] args) {
        StringBuilder stringBuilder = new StringBuilder("");
        int count = 100000;
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < count; i++) {
            stringBuilder.append(i);
        }
        long endTime = System.currentTimeMillis();
        System.out.println(endTime-startTime); //4
    }

2.获取底层保存字符串空间总的大小与扩容

java 复制代码
    public static void main(String[] args) {
        StringBuilder stringBuilder = new StringBuilder("hello");
        //获取底层保存字符串空间总的大小
        System.out.println(stringBuilder.capacity()); //21
        stringBuilder.ensureCapacity(100);
        //扩容
        System.out.println(stringBuilder.capacity()); //100
    }

3.通过索引位置修改字符串

java 复制代码
    public static void main(String[] args) {
        StringBuilder stringBuilder = new StringBuilder("hello");
        //将索引为1的位置设置为x
        stringBuilder.setCharAt(1,'x');
        System.out.println(stringBuilder); //hxllo
    }

4.插入

java 复制代码
    public static void main(String[] args) {
        StringBuilder stringBuilder = new StringBuilder("hello");
        //在索引1位置插入xxxx
        stringBuilder.insert(1,"xxxx");
        System.out.println(stringBuilder); //hxxxxello
    }

5.删除

java 复制代码
    public static void main(String[] args) {
        StringBuilder stringBuilder = new StringBuilder("helloworld");
        //删除索引1到3的字符
        stringBuilder.delete(1,4);
        System.out.println(stringBuilder); //howorld
    }

6.替换

java 复制代码
    public static void main(String[] args) {
        StringBuilder stringBuilder = new StringBuilder("helloworld");
        //将索引1到3的内容替换为aaaa
        stringBuilder.replace(1,4,"aaaa");
        System.out.println(stringBuilder); //haaaaoworld
    }

7.逆转

java 复制代码
    public static void main(String[] args) {
        StringBuilder stringBuilder = new StringBuilder("hello");
        System.out.println(stringBuilder.reverse()); //olleh
    }
相关推荐
Chester_19997 小时前
CSP202203C.计算资源调度器
开发语言·数据结构·c++·蓝桥杯
EXI-小洲8 小时前
Java 操作 Word:字符串替换、图片插入、动态生成表格与API接口下载
java·开发语言·spring boot·word
会周易的程序员8 小时前
给 PLC 写一个字节码虚拟机:STVM 虚拟机架构设计
开发语言·c++·虚拟机·软plc·iec61131·stvm
机器视觉知识推荐、就业指导8 小时前
为什么老说“纯 Qt 没啥就业市场”?
开发语言·qt
telepan8 小时前
Qt 开发避坑与性能指南:如何优雅、安全地定义全局常量字符串?
开发语言·qt
m0_695251499 小时前
Qt MaintenanceTool 使用国内镜像加速下载(超详细教程)
开发语言·qt
2601_961901709 小时前
SpringBoot使用Nacos进行application.yml配置管理
java·spring boot·spring
是隼人9 小时前
buuctf-pwn xdctf2015_pwn200题解(学习过程持续更新)
c语言·学习·安全·pwn入门·ctf入门
何以解忧,唯有..10 小时前
LangChain 工具调用(Tool Calling)实战指南
java·前端·langchain
大衛說10 小时前
《Python 从入门到精通》系列总览与学习路线
开发语言·python·学习