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
    }
相关推荐
Aric_Jones2 小时前
博客音乐播放器实现全解析
java·运维·数据库·人工智能·docker·容器·eclipse
2501_941982052 小时前
Python开发:实现企微外部群消息关键词监控
java·服务器·数据库
brucelee1862 小时前
Java 开发AWS Lambda 实战指南(SAM CLI + IntelliJ)
java·开发语言
码云数智-大飞2 小时前
Nginx负载均衡四大核心算法深度解析:原理、配置与选型实战
java
tobias.b2 小时前
408真题解析-2010-37-计算机网络-子网划分与CIDR
开发语言·计算机网络·计算机考研·408真题解析
消失的旧时光-19432 小时前
第二十一课:系统是怎么一步步拆坏的?——单体到模块化实践(完整工程版)
java·spring boot·后端·架构
纯.Pure_Jin(g)2 小时前
【Python练习五】Python 正则与网络爬虫实战:专项练习(2道经典练习带你巩固基础——看完包会)
开发语言·vscode·python
WZ188104638692 小时前
软件测试人员怎样学习AI
人工智能·学习
hoiii1872 小时前
基于C#实现的高性能实时MP4录屏方案
开发语言·c#