【Java】字符串String

目录

1.字符串的构造

2.字符串转换 

2.1字符串与数值转换

2.2大小写转换 

2.3字符串转数组 

2.4格式化 

3.字符串操作

3.1字符串比较

3.2字符串查找

3.3字符串替换

3.4字符串拆分

3.5字符串截取 

3.6去除空格

4.字符串的不可变性

5.字符串修改

5.1StringBuffer的高效率

5.2 常用方法

6.小练习oj


1.字符串的构造

Ctrl 进入后我们看见String类是被final修饰的,说明不可以被继承

后面的Comparable接口说明字符串支持比较大小

public class Main {
    public static void main(String[] args) {
        String str1 = "hello";
        String str2 = new String("hello");//同上
        char[] arr = {'a','b','c','d'};//Java中没有“字符串以'\0'结尾”这一概念
        String str3 = new String(arr);
        System.out.println(str1);
        System.out.println(str2);
        System.out.println(str3);//abcd
        String str4 = "";//str4指向的对象中没有任何数据
        String str5 = null;//str5不指向任何对象
        System.out.println(str4.isEmpty());//true
        //System.out.println(str5.isEmpty());//空指针异常
        System.out.println("hello".length());
    }
}

2.字符串转换 

2.1字符串与数值转换

class Student {
    public String name;
    public int age;
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
public class Test {
    public static void main(String[] args) {
        //其他类型转字符串
        String s1 = String.valueOf(12345);
        String s2 = String.valueOf(true);
        String s3 = String.valueOf(new Student("zhangsan",18));
        System.out.println(s1);//12345
        System.out.println(s2);//true
        System.out.println(s3);//Student{name='zhangsan', age=18}
        //字符串转数字
        int data1 = Integer.valueOf("123");
        int data2 = Integer.parseInt("456");
        System.out.println(data1);//123
        System.out.println(data2);//456
    }
}

2.2大小写转换 

public class Test {
    public static void main(String[] args) {
        String s1 = "hello";
        String s2 = "WORLD";
        System.out.println(s1.toUpperCase());//小写转大写
        System.out.println(s2.toLowerCase());//大写转小写
        String ret1 = s1.toUpperCase();//两种方法都可以
        String ret2 = s2.toLowerCase();
        System.out.println(ret1);
        System.out.println(ret2);
    }
}

2.3字符串转数组 

import java.util.Arrays;
public class Test {
    public static void main(String[] args) {
        String str = "hello world";
        char[] arr = str.toCharArray();
        System.out.println(Arrays.toString(arr));//[h, e, l, l, o,  , w, o, r, l, d]
    }
}

2.4格式化 

public class Test {
    public static void main(String[] args) {
        String str = String.format("%d %d %d",2023,5,4);//类似于C语言
        System.out.println(str);//2023 5 4
    }
}

3.字符串操作

3.1字符串比较

public class Main {
    //1.比较相等
    public static void main(String[] args) {
        String str1 = new String("hello");
        String str2 = new String("hello");
        System.out.println(str1 == str2);//false---比较的是两个字符串的地址
        System.out.println(str1.equals(str2));//true---String中重写了equals方法,比较的是内容

        String str3 = "abc";//和上面不同,这里是直接赋值
        String str4 = "abc";//str3和str4指向的是同一块内存
        System.out.println(str3 == str4);//true---常量池的概念
    }
    //2.比较大小
    public static void main1(String[] args) {
        String str1 = "abcde";
        String str2 = "abde";
        System.out.println(str1.compareTo(str2));//-1
        String str3 = "abcd";
        String str4 = "abCd";
        System.out.println(str3.compareTo(str4));//32
        System.out.println(str3.compareToIgnoreCase(str4));//0---忽略大小写
    }
}

3.2字符串查找

方法功能
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
public class Test {
    public static void main(String[] args) {
        String str = "hello";
        char ch = str.charAt(1);
        System.out.println(ch);//e

        System.out.println(str.indexOf('l'));//2
        System.out.println(str.indexOf('l', 3));//3
        System.out.println(str.indexOf("ll"));//2
        System.out.println(str.indexOf("ll", 3));//-1

        System.out.println(str.lastIndexOf('l'));//3
        System.out.println(str.lastIndexOf('l',2));//2
        System.out.println(str.lastIndexOf("ll"));//2
        System.out.println(str.lastIndexOf("ll",1));//-1
    }
}

3.3字符串替换

public class Test {
    public static void main(String[] args) {
        String s1 = "abcdabvdabcd";
        String ret1 = s1.replace('a','o');//替换单个字符
        String ret2 = s1.replace("ab","oo");//替换所有字符
        String ret3 = s1.replaceFirst("ab","oo");//替换第一次出现的字符
        String ret4 = s1.replaceAll("ab","oo");//替换所有字符
        System.out.println(ret1);//obcdobvdobcd
        System.out.println(ret2);//oocdoovdoocd
        System.out.println(ret3);//oocdabvdabcd
        System.out.println(ret4);//oocdoovdoocd
    }
}

3.4字符串拆分

注意:正则表达式

1> 字符 ' | ',' * ',' . ',' + ' 都要加上' \\ ';

2> ' \ ' 就要写成 ' \\\\ ';

3> 如果一个字符串中有多个分隔符,用 ' | ' 作为连字符。

public class Test {
    public static void main(String[] args) {
        String str1 = "hello world I love coding";
        String[] ret1 = str1.split(" ");//以空格分割
        String[] ret2 = str1.split(" ",2);//限制分为两组,但不会均分
        System.out.println(Arrays.toString(ret1));//[hello, world, I, love, coding]
        System.out.println(Arrays.toString(ret2));//[hello, world I love coding]

        String str2 = "2023.5.4";
        String[] ret3 = str2.split("\\.");//注意!!
        System.out.println(Arrays.toString(ret3));//[2023, 5, 4]

        String str3 = "abc\\def\\ghi";
        String[] ret4 = str3.split("\\\\");
        System.out.println(Arrays.toString(ret4));//[abc, def, ghi]

        String str4 = "abcd&1234*ABCD";
        String[] ret5 = str4.split("&|\\*");
        System.out.println(Arrays.toString(ret5));//[abcd, 1234, ABCD]
    }
}

3.5字符串截取 

public class Test {
    public static void main(String[] args) {
        String str = "hello";
        String ret1 = str.substring(1);
        String ret2 = str.substring(1,3);//注意左闭右开[1,3)
        System.out.println(ret1);//ello
        System.out.println(ret2);//el
    }
}

3.6去除空格

public class Test {
    public static void main(String[] args) {
        String str = "  hell o wor l d    ";
        String ret = str.trim();//去除左右空格,保留中间空格
        System.out.println(ret);//hell o wor l d
    }
}

4.字符串的不可变性

Ctrl 进入后我们发现:

1> String类中的字符实际保存在内部维护的value字符数组中;

2> value被final修饰,表明value自身的值不能改变,即不能引用其他字符数组,但是其引用空间中的内容可以修改;

3> 所有对String的修改,都不是在原有的基础上改动,而是创建新对象,改变新对象

String类为何设计成不可变的?(后续讲解)

1> 方便实现字符串对象池;

2> 不可变对象是线程安全的;

3> 不可变对象更方便缓存 hash code,作为key时可以更高效的保存到HashMap中。

public class Main {
    public static void main(String[] args) {
        final int[] arr = {1,2,3,4,5};
        arr[0] = 10;//引用对象中的内容可以修改
        System.out.println(Arrays.toString(arr));
        //arr = new int[]{6,7,8,9};//该引用变量不能引用其他对象
    }
}

5.字符串修改

因为String类的不可变性,应尽量避免直接对String类对象进行修改,又因为所有的修改都会创建新的对象,效率十分低下。这时候就需要 StringBuilderStringBuffer 出马了~

StringBuffer 和 StringBuilder大部分功能相似区别:StingBuffer采用同步处理(同步:synchronized),属于线程安全操作,但更低效;而StringBuilder未采用同步处理,属于线程不安全操作。

与String的区别:String的内容不可修改,这俩的内容可以修改。

以下均用StringBuffer 指代: 

5.1StringBuffer的高效率

public class Main {
    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);//222
        //StringBuffer
        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);//0
        //StringBuilder
        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);//1
    }
}

222---1---0,1和0之间的差距可忽略不计。由此可见,这俩的效率可不是一般的高。 

5.2 常用方法

方法说明
StringBuffer append ( String str )在尾部追加,相当于 String 的+=
StringBuffer insert ( int offset, String str )在 offset 位置插入 str
StringBuffer deleteCharAt ( int index )删除 index 位置的字符
StringBuffer delete ( int start, int end )删除 [ start, end ) 区间内的字符
StringBuffer replace ( int start, int end, String str )将 [ start, end ) 位置的字符替换为str
StringBuffer reverse ()反转字符串
String toString ()将所有字符按照 String 方式返回
public class Main {
    public static void main(String[] args) {
        StringBuffer stringBuffer = new StringBuffer("hello");
        stringBuffer.insert(1,"abc");
        System.out.println(stringBuffer);//habcello
        stringBuffer.delete(1,3);//[1,3)
        System.out.println(stringBuffer);//hcello
        stringBuffer.reverse();
        System.out.println(stringBuffer);//ollech
        stringBuffer.append("world");
        System.out.println(stringBuffer);//ollechworld
        String str = stringBuffer.toString();//将所有字符按照String的方式返回
    }
}

6.小练习oj

字符串中的第一个唯一字符

字符串最后一个单词的长度

验证回文串


还有最后一个异常,JavaSE就结束啦!哦吼吼嘿嘿~~

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值