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
    }
相关推荐
不听话坏4 分钟前
Ignition篇(下 一) 动态执行前的事情
开发语言·前端·javascript
likeyi0715 分钟前
require 和 import的区别
开发语言·前端
咖啡八杯32 分钟前
GoF设计模式——迭代器模式
java·后端·设计模式·迭代器模式
远离UE438 分钟前
UE5 compute shader 原子加
开发语言·c++·ue5
C+-C资深大佬40 分钟前
C++ 显式类型转换详解:static_cast、dynamic_cast、const_cast、reinterpret_cast
开发语言·c++
AIGS0011 小时前
企业AI落地的关键认知:向量空间JBoltAI的本体语义平台
java·人工智能·人工智能ai大模型应用
KaMeidebaby2 小时前
卡梅德生物技术快报|抗体亲和力成熟工业化调控新机制:差异性浆细胞增殖工艺优化思路
java·开发语言·人工智能·算法·机器学习·架构·spark
心中有国也有家2 小时前
AtomGit Flutter 鸿蒙客户端: ChangeNotifier 模式
学习·flutter·华为·harmonyos
luj_17682 小时前
心形曲线轨迹控制三大关键技术
c语言·开发语言·c++·经验分享·算法
取地址符2 小时前
C++学习笔记(基于learn-cxx)(1)
c++·经验分享·笔记·学习