java基础-基础API与常见算法

基础API与常见算法


和数学相关的类

数学类Math:构造器私有,方法都是静态方法

//静态导入:导入某一个类中的静态资源,可以省略类名直接调用
import static java.lang.Math.*;
public class MathTest {
    public static void main(String[] args) {
        //绝对值
        System.out.println(Math.abs(-1));// 1
        //向上取整
        System.out.println(Math.ceil(3.14));// 4.0
        //向下取整
        System.out.println(Math.floor(9.8));// 9.0
        //随机数[0,1);       [m,n]:(int)(Math.random()*(n-m+1)+m);
        System.out.println(Math.random());
        //求平方
        System.out.println(Math.pow(2, 4));// 16.0
        //开平方
        System.out.println(Math.sqrt(9));// 3.0
        //四舍五入
        System.out.println(Math.round(3.14));// 3
        //圆周率
        System.out.println(Math.PI);// 3.141592653589793

        System.out.println(PI);//静态导入后可以省略类名直接调用
    }
}

BigInteger类:存储大的整数

import java.math.BigInteger;

public class BIgTest {
    public static void main(String[] args) {
        /*
     BigInteger 大的整数
     存储大的整数
     */
        System.out.println(Long.MAX_VALUE);//9223372036854775807
        BigInteger bigInteger = new BigInteger("9223372036854775807123");
        System.out.println(bigInteger);//9223372036854775807123

        //基本数据类型
        int a = 10;
        int b = 20;
        System.out.println(a + b);//30

        //引用数据类型
        BigInteger b1 = new BigInteger("10");
        BigInteger b2 = new BigInteger("20");
        //System.out.println(b1 + b2);引用数据类型不能直接相加
        System.out.println("加法"+b1.add(b2));//30
        System.out.println("减法"+b1.subtract(b2));//-10
        System.out.println("乘法"+b1.multiply(b2));//200
        System.out.println("除法"+b1.divide(b2));// 0
        System.out.println("取余"+b1.remainder(b2));//10
    }
}

RoundingMode枚举类

在这里插入图片描述

BigDecimal类:用于存储确切的小数

import java.math.BigDecimal;
public class BIgTest {
    public static void main(String[] args) {
        BigDecimal b3 = new BigDecimal("10");
        BigDecimal b4 = new BigDecimal("20");
        System.out.println("加法"+b3.add(b4));//30
        System.out.println("减法"+b3.subtract(b4));//-10
        System.out.println("乘法"+b3.multiply(b4));//200
        System.out.println("除法"+b3.divide(b4));//0.5
        System.out.println("取余"+b3.remainder(b4));//10

        BigDecimal b5 = new BigDecimal("10.0");
        BigDecimal b6 = new BigDecimal("3.0");
        //不能整除要放入舍入模式
        System.out.println(b5.divide(b6,10,BigDecimal.ROUND_FLOOR));//3.3333333333
        System.out.println(b5.divide(b6,BigDecimal.ROUND_FLOOR));//3.3
        System.out.println(b5.divide(b6,BigDecimal.ROUND_CEILING));//3.4
    }
}

Random类

import java.util.Random;
public class Test{
	public static void main(String [] args){
	//当种子固定的时候,产生的随机数是相同的:Random random = new Random(1);
		Random random = new Random();
        //random.nextInt(n)     [0,n)范围内的int类型的随机数
        for (int i = 0; i < 10; i++) {
            //System.out.println(random.nextDouble());//[0,1)
            //System.out.println(random.nextBoolean());//true false
            System.out.println(random.nextInt(10));
	}
}

日期时间API

jdk1.8前

Date类
import java.util.Date;

public class DataTest {
    public static void main(String[] args) {
        //过时方法
        Date date = new Date();
        System.out.println(date);
        System.out.println("年:"+(date.getYear()+1900));//+1900表示现在年
        System.out.println("月:"+(date.getMonth()+1));//0代表1月
        System.out.println("日:"+date.getDate());
        System.out.println("一周的第几天:"+date.getDay());

        long time = date.getTime();//当前时间转换毫秒数
        System.out.println(time);
        Date date1 = new Date(1654519577433L);//毫秒数转日期
        System.out.println(date1);

        String string = date1.toLocaleString();
        System.out.println(string);//2022-6-6 20:46:17

        //同一个类中需要同名对象需要全路径导入
        //只有年月日没有时分秒
        java.sql.Date date2 = new java.sql.Date(1654519577433L);
        System.out.println(date2);//2022-06-06

    }
}
Calendar类
import java.util.Calendar;
public class DataTest {
    public static void main(String[] args) {
//Calender抽象类 不能直接创建对象,需要通过子类实现功能,
        // 或者调用getInstance()方法创建Calender对象
        Calendar calendar = Calendar.getInstance();
        System.out.println(calendar);//获取全部信息
        System.out.println(calendar.get(Calendar.YEAR));//月从0开始
        //修改日期   calendar.add(属性,值);
        calendar.add(Calendar.YEAR,2);//2022+2
        System.out.println(calendar.get(Calendar.YEAR));//2024
        //设置指定日期
        calendar.set(2000,1,1);
    }
}
获取时区:了解
String[] availableIDs = TimeZone.getAvailableIDs();
        for (String availableID:availableIDs) {
            System.out.println(availableID);
        }
日期格式化
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DataTest {
    public static void main(String[] args) throws ParseException {
/*
        * 日期转换
        * 新建日期格式化对象
        *  DateFormat df =new SimpleDateFormat("格式");
            日期转字符串
            * df.format(日期对象);
            * date--》2022-06-07 10:00:16 星期二
            *
            * 字符串转日期
            * Date date = df.parse(字符串)
            * 要解析的字符串内容必须与格式完全匹配,否则报错:
            * ParseException: Unparseable date: "2022-06-0710:00:16"
         * */
        //hh:12小时制 HH:24小时制
        DateFormat df =new SimpleDateFormat("yyyy-MM-dd hh:mm:ss E");
        Date date =new Date();
        String s = df.format(date);
        System.out.println(s);

        String ss = "2022-06-07 10:00:16";//字符串格式与日期格式化格式必须一直
        //新建日期格式化对象
        DateFormat d =new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date date1 = d.parse(ss);//编译时异常
        System.out.println(date1);
   }
}

jdk1.8后

本地日期时间
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Month;

public class NewDate {
    public static void main(String[] args) {
        /*
            LocalDate:年月日
            不可变的日期,一旦对日期做出修改,会生成一个新的LocalDate记录改变后的日期
            minusDays:日期减少
            plusDays:日期增加
        */
        LocalDate of = LocalDate.of(2019,1,1);
        System.out.println(of);//输出指定日期
        LocalDate now = LocalDate.now();
        System.out.println(now);//输出现在年月日
        int year = now.getYear();
        System.out.println(year);//输出年
        Month month = now.getMonth();
        System.out.println(month.getValue());//输出月
        System.out.println(now.getDayOfMonth());//输出日

        //让当前日期-2
        LocalDate localDate = now.minusDays(2);
        System.out.println(localDate);//
        //让当前日期+2
        LocalDate localDate1 = now.plusDays(2);
        System.out.println(localDate1);

        LocalTime of1 = LocalTime.of(5,1,1,3);
        System.out.println(of1);//设置指定时间

        LocalTime localTime = LocalTime.now();
        System.out.println(localTime);//输出当前时分秒毫秒
        System.out.println(localTime.getHour());//输出时
        System.out.println(localTime.getMinute());//输出分
        System.out.println(localTime.getSecond());//输出秒


    }
}
指定时区日期时间:了解
ZonedDateTime now = ZonedDateTime.now();
        System.out.println(now);
ZonedDateTime now1 = ZonedDateTime.now(ZoneId.of("America/New_York"));
        System.out.println(now1);
持续日期/时间:Period和Duration
import java.time.*;

public class NewDate {
    public static void main(String[] args) {
//计算日期差
        LocalDate l1 = LocalDate.now();
        LocalDate l2 = LocalDate.of(2019,1,1);
        Period between = Period.between(l2, l1);
        System.out.println(between);
        System.out.println(between.getYears());//差几年
        System.out.println(between.getMonths());//差几月
        System.out.println(between.getDays());//差几日

        //计算时间差
        LocalDateTime l3 = LocalDateTime.now();
        LocalDateTime l4 = LocalDateTime.of(2019,2,2,2,2,2);
        Duration duration = Duration.between(l4, l3);
        System.out.println(duration);
        //获取两个时间段相隔多少天
        System.out.println(duration.toDays());
    }
}
日期格式化类:DateTimeFormatter类
//DateTimeFormatter有提供好的模板,直接使用;将日起对象转为字符串
        DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE;
        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println(formatter.format(localDateTime));

        //自定义
        DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        System.out.println(formatter1.format(localDateTime));

        //将字符串转为日期
        //新的日期格式化小时使用HH
        String string = "2022-06-07 12:22:29";
        LocalDateTime localDateTime1 = LocalDateTime.parse(string, formatter1);
        System.out.println(localDateTime1);

系统相关类

System类&Runtime类

import java.util.Properties;

public class Test {
    public static void main(String[] args) {
        //获取当前时间的毫秒数
        long l = System.currentTimeMillis();
        System.out.println(l);
        System.gc();//运行垃圾收集器

        int[] arr = {1,2,3};
        int[] newArr = new int[arr.length];
        //赋值字符串
        System.arraycopy(arr,0,newArr,0,3);
        for (int i : newArr) {
            System.out.println(i);
        }

        Properties properties = System.getProperties();
        properties.list(System.out);//所有java系统属性
        System.out.println(System.getProperty("java.version"));

        //Runtime类:了解
        Runtime r1 = Runtime.getRuntime();
        Runtime r2 = Runtime.getRuntime();
        System.out.println(r1 == r2);//true

        System.out.println(r1.totalMemory());//总运行内存
        System.out.println(r1.freeMemory());//剩余空闲运行内存
    }
}

数组的算法升华

数组的交换

import java.util.Arrays;

public class Test {
    public static void main(String[] args) {
        int[] arr = {1,2,3,4,5,6,7,8};
        System.out.println("交换前"+Arrays.toString(arr));
        //首尾交换,只需一般数据交换
        for (int i = 0; i < arr.length/2; i++) {
            int temp = arr[i];
            arr[i] = arr[arr.length-i-1];
            arr[arr.length-i-1] = temp;
        }
        System.out.println("交换后"+Arrays.toString(arr));
    }
}

二分查找

/*二分查找
             前提:数据必须有序,从小到大的顺序
        */
public class BinarySearch {
    public static void main(String[] args) {
        int[] arr = {1,2,3,4,5,6,7,8,9,10};
        int index = binarySearch1(arr, 9);
        if (index != -1){
            System.out.println("指定元素对应的下标是:"+index);
        }else {
            System.out.println("无此元素");
        }
    }

    /**
     *二分查找法
     * @param arr 要查找的数组
     * @param i 要查找的元素
     */
    private static int binarySearch1(int[] arr, int i) {
        //获取开始下标和结束下标
        int startIndex = 0;
        int endIndex = arr.length-1;
        //使用循环完成
        while (startIndex<=endIndex){
            //获取中间下标
            int midIndex = (startIndex+endIndex)/2;
            //找到中间下标对应的元素
            int midValue = arr[midIndex];
            //当要查找的元素 > 中间下标对应的元素 :开始下标 = 中间下标+1
            if (i > midValue) {
                startIndex = midIndex+1;
            }//当要查找的元素 < 中间下标对应的元素 :结束下标 = 中间下标-1
            else if(i < midIndex){
                endIndex = midIndex-1;
            } //当要查找的元素 == 中间下标对应的元素
            else {
                return midIndex;
            }
        }
        return -1;
    }
}

数组的扩容

public class DilatationArr {
    public static void main(String[] args) {
        //当原来的数组长度不够了需要扩容
        //旧数组
        String[] strArr = {"张三","李四","王五"};
        //扩容
        String[] newArr = new String[strArr.length+1];
        System.arraycopy(strArr,0,newArr,0,strArr.length);
        //新增元素
        newArr[3] = "赵六";
        //把新数组的地址赋值给旧数组
        strArr = newArr;
        for (String s : strArr) {
            System.out.println(s);
        }
    }
}

数组的插入

public class ArrInsert {
    public static void main(String[] args) {
        //数组元素的插入 数组未满 数组已满
        //1、数组未满
        String [] arr = new String[5];
        arr[0] = "张三";
        arr[1] = "李四";
        arr[2] = "王五";
        //下标为1 的位置插入元素
        System.arraycopy(arr,1,arr,2,2);
        arr[1] = "赵六";
        for (String s : arr) {
            System.out.println(s);
        }

        //2、数组已满 再次插入数据要进行扩容
        String [] arr1 = {"张三","李四","王五"};
        //在下标为1的位置插入元素
        String [] newArr = new String[arr1.length+1];
        System.arraycopy(arr1,0,newArr,0,1);
        System.arraycopy(arr1,1,newArr,2,2);
        newArr [1] = "赵六";
        arr1 = newArr;
        for (String s : arr1) {
            System.out.println(s);
        }
    }
}

数组元素的删除

public class ArrDelete {
    public static void main(String[] args) {
        String [] arr = {"张三","李四","王五"};
        /*
            思路一:
            新建一个新数组,存储俩元素
            将删除元素前后的元素放到新数组内
            将新数组的地址赋给旧数组
            遍历旧数组

            思路二:
            在数组arr里将 王五向前移动一位 ,元素3的位置为null 即为删除李四
        */
        System.arraycopy(arr,2,arr,1,1);
        arr[2] = null;
        for (String s : arr) {
            System.out.println(s);
        }
    }
}

选择排序

import java.util.Arrays;

public class SelectionSort {
    public static void main(String[] args) {
        int[] arr = {1,8,9,2,6,7,5,3,4,10};
        for (int i = 0; i < arr.length - 1; i++) {
            //假设此位置就是最小值
            int minIndex = i;
            //假设的值与假设之后的值比较
            for (int j = i+1; j < arr.length; j++) {
                //进行比较,找真正最小值的下标
                //如果一个数比假设的最小值小,说明此数是小数
                if (arr[j]<arr[minIndex]) {
                    //切换最小值的下标
                    minIndex = j;
                }
            }
            //循环结束后,假设的最小值的下标发生了变化,则进行交换俩数的位置
            if (minIndex != i) {
                int temp = arr[i];
                arr[i] = arr[minIndex];
                arr[minIndex] = temp;
            }
            System.out.println("排序中"+Arrays.toString(arr));
        }
        //遍历排序后数组
        for (int i : arr) {
            System.out.println(i);
        }
    }
}

数组的工具类:Arrays

熟练掌握:toString()、sort()、copyOf()、binarySearch()

import java.util.Arrays;

/*
    如果比较是系统类型可直接使用Arrays.sort()
    如果是自定义类型:
    Student[] ss = {s1,s2,s3};
    自定义类实现了Comparable接口
    Arrays.sort(ss);

    自定义类没有实现Comparable接口
     Arrays.sort(ss,比较规则);
*/
public class ArrayTest {
    public static void main(String[] args) {
        int[] arr = {6,5,4,3,2,1};
        System.out.println(Arrays.toString(arr));//输出数组     [6, 5, 4, 3, 2, 1]
        //Arrays.sort(排序的数组,开始的下标,结束的下标);  [开始下标,结束下标)
        Arrays.sort(arr,0,4);
        System.out.println(Arrays.toString(arr));//[3, 4, 5, 6, 2, 1]
        Arrays.sort(arr);//从小到大排序
        System.out.println(Arrays.toString(arr));//[1, 2, 3, 4, 5, 6]

        int[] arr1 = new int[5];
        Arrays.fill(arr1,10);//填充数组
        System.out.println(Arrays.toString(arr1));//[10, 10, 10, 10, 10]
        //按照指定范围填充元素 Arrays.fill(数组名,开始下标,结束下标,填充元素);
        Arrays.fill(arr1,0,3,20);//[0,3)填充数组
        System.out.println(Arrays.toString(arr1));//[20, 20, 20, 10, 10]

        String[] s = {"张三","李四","王五"};
        //复制旧数组,创建一个新数组,改动新数组不会对旧数组造成影响
        String[] ss = Arrays.copyOf(s,2);
        //复制指定范围的数组Arrays.copyOfRange(数组名, 开始下标, 结束下标);
        String[] sss = Arrays.copyOfRange(s, 0, 1);//[0,1)
        System.out.println(Arrays.toString(s));//[张三, 李四, 王五]
        System.out.println(Arrays.toString(ss));//[张三, 李四]
        System.out.println(Arrays.toString(sss));//[张三]

        int[][] arrInt = {{1,2},{3,4},{5,6}};
        //遍历二维数组Arrays.deepToString(数组名)
        System.out.println(Arrays.deepToString(arrInt));

        int[] a1 ={1,2};
        int[] a2 ={1,2};
        System.out.println(a1 == a2);//false :比较的是地址值
        //Arrays.equals(a1, a2);比较的内容和下标必须完全一样才会是true
        System.out.println(Arrays.equals(a1, a2));//true

        //二分查找 前提数组必须有序 返回-1 说明数组内不含此元素
        int[] arrInt1 = {2,4,6,7,1,3,5,6};
        Arrays.sort(arrInt1);
        System.out.println(Arrays.toString(arrInt1));//[1, 2, 3, 4, 5, 6, 6, 7]
        System.out.println(Arrays.binarySearch(arrInt1, 3));//2
    }
}

java.lang.String

String类是一个final类,不能被继承
String是不可变的字符序列,任何一次操作的产生都是新的对象
String字符串的底层采用的是char[]数组存储数据(jdk1.9char[]–>byte[])

package string;
/*字符串的创建*/
public class StringTest {
    public static void main(String[] args) {
        //1、字符串常量对象,1个,在常量池中
        String mess = "你好";
        //2
        char[] c = {'a','b'};
        String s = new String(c);
        System.out.println(s);
        String s5 = new String(c, 0, 1);
        System.out.println(s5);
        //3、字符串的普通对象和常量对象一起
        //s1首先指向堆中的一个字符串对象,然后堆中字符串的value数组指向常量池中常量对象的value数组
        String s1 = new String("你好");
        System.out.println(s1);
        //4、创建一个空的字符串
        String s2 = new String();
        System.out.println("s2=" + s2 + "=s2");
        //5、注意会将byte类型中数字解析成对应的字符
        byte[] bytes = {65,66,67,97};
        String s3 = new String(bytes);
        System.out.println(s3);
        //String s4 = new String(byte类型的数组, 开始的下标, 获取几个元素);
        String s4 = new String(bytes, 0, 2);
        System.out.println(s4);


        int a = 10;
        String s6 = ""+a;
        String s7 = String.valueOf(a);
        System.out.println(s6 +" "+ s7);


		String ss1 = "hello";//字符串变量s1 ---> "helLo"在常量池中的位置
        String ss2 = "world" ;//字符串变量s2---> "world"在常量池中的位置
        String ss3 = "hello" + "world" ;//常量+常量==>常量
        String ss4 = "helloworld" ;// helloworld字符串常量
        String ss5 = ss1 + ss2;//变量+变量在堆中
        String ss6 = ss1 + "wor1d" ;//变量+常量在堆中
        System.out.println(ss3 == ss4); //true
        System.out.println(ss5 ==ss4);//false
        System.out.println(ss6 == ss5);//false
        System.out.println(ss6 == ss4);//false
		
		String hello = new String(  "hello");
        System.out.println(hello == ss1);//false
        // hello.intern()调用此方法会将数据直接存到常量池
        System.out.println(hello.intern() == ss1);//true

    }
}
String常用方法
import java.util.Arrays;

public class StringMethod {
    public static void main(String[] args) {
        //字符串所有方法不会对原有数据造成影响,都是新建一个去做
        int[] arrInt = {1,2};
        System.out.println("arrInt.length = " + arrInt.length);
        String mess = "你好";
        System.out.println("mess.length() = " + mess.length());

        String s2 = "world";
        String s3 = mess+s2;
        String s5 ="你好world";
        System.out.println("s3 = " + s3);
        //合并字符串
        String s4 = mess.concat(s2);
        System.out.println("s4 = " + s4);
        System.out.println(s5==s4);//false
        //小写全变大写
        String s = s2.toUpperCase();
        System.out.println("s = " + s);//s = WORLD
        //大写全变小写
        String s1 = s.toLowerCase();
        System.out.println("s1 = " + s1);//s1 = world

        String ss = "abcDEF";
        String ss1 = "ABCdef";
        //严格区分大小写
        System.out.println("ss.equals(ss1) = " + ss.equals(ss1));//ss.equals(ss1) = false
        //忽略大小写比较
        System.out.println("ss.equalsIgnoreCase(ss1) = " + ss.equalsIgnoreCase(ss1));//ss.equalsIgnoreCase(ss1) = true


        String m1 = "a";
        String m2 = "c";
        System.out.println(m1.compareTo(m2) + "  " + m2.compareTo(m1));//-2  2
        String[] arr = {"b","a","z","h"};
        Arrays.sort(arr);
        System.out.println(Arrays.toString(arr));//[a, b, h, z]


        // trim()去除字符串两端的空格
        String sss = " A B C ";
        System.out.println("---"+sss+"---");//--- A B C ---
        String trim = sss.trim();
        System.out.println("---"+trim+"---");//---A B C---

    }
}
package string;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;

public class StringMethod2 {
    public static void main(String[] args) throws UnsupportedEncodingException {
        String mess = "hello";
        //判断是否包含指定的字符串
        System.out.println(mess.contains("hel"));//true
        //查找指定元素第一次出现的下标(不存在返回-1)
        System.out.println(mess.indexOf("l"));//2
        //查找指定元素最后一次出现的下标(不存在返回-1)
        System.out.println(mess.lastIndexOf("l"));//3

        //从指定下标截取到末尾
        System.out.println(mess.substring(1));//ello
        //截取指定范围的字符串[开始下标,结束下标)
        System.out.println(mess.substring(1, 3));//el

        //获取指定位置的字符
        System.out.println(mess.charAt(mess.length() - 1));//o
        //将字符串转为char类型数组
        System.out.println(Arrays.toString(mess.toCharArray()));//[h, e, l, l, o]
        

		String mess2 = "ABCDE";
        //判断是否以指定的内容开头
        System.out.println(mess2.startsWith("ABC"));//true
        //判断是否以指定的内容结尾
        System.out.println(mess2.endsWith("DE"));//true
        
		//替换字符串,如果查找内容不存在则返回原字符串
        System.out.println(mess2.replace("A", "eee"));//eeeBCDE


		//编码与解码
        String mess1 = "你好";
        byte[] bytes = mess1.getBytes();
        System.out.println("Arrays.toString(bytes) = " + Arrays.toString(bytes));
        byte[] messBytes = mess.getBytes("iso8859-1");
        System.out.println(Arrays.toString(messBytes));
        System.out.println(mess1.getBytes( "gbk").length);//一个汉字俩字节 4 一个字母一个字节
        System.out.println(mess1.getBytes( "utf-8").length);//一个汉字三个字节 6 一个字母一个字节

    }
}
正则
package string;

import java.util.Arrays;

public class StringMethod3 {
    public static void main(String[] args) {
        /*
            正则:独立的语言
            文本校验
            判断输入的文本是否满足要求

            []:代表一个字符
            [a-z]:小写字母a-z任意一个都可以
            +:一个或多个
            *:0个或多个
            ?:0个或1个
            [^a]:代表匹配不是a的数据
            java里要加\转义 例:\\d
            \d:代表任意一个数字0-9
            \w:代表字母和数字以及下划线
            ^ :代表什么开始
            $:以什么结尾
        */
        String mess = "abc";
        System.out.println(mess.matches("[a-z]+"));//true
        System.out.println(mess.matches("[^a]+"));//false

        String mess1 = "01";
        System.out.println(mess1.matches("\\d+"));//true

        //匹配手机号
        String ss = "17678900944";
        System.out.println(ss.matches("1[3578]\\d{9}"));//true

        String str = "hello23091wor.;090ld";
        //除了字母全部去掉
        System.out.println(str.replaceAll("[^a-zA-Z]+", ""));//helloworld

        String sss = "a1b1c";
        //按照指定的要求进行切割
        String[] split = sss.split( "1");
        System.out.println(Arrays.toString(split));//[a, b, c]

        String mess2 ="AB1CD3jk8op" ;
        //按照数字进行切割
        String[] split1 = mess2.split("\\d");
        System.out.println( Arrays.toString(split1));//[AB, CD, jk, op]

        String mess3="1AB1cD32jk8op2";
        //"^\d|\d$"以数字开头或者以数字结尾
        String s = mess3.replaceAll("^\\d|\\d$", "");//AB1cD32jk8op
        System.out.println(s);
        System.out.println(Arrays.toString(s.split("\\d+")));//[AB, cD, jk, op]


    }
}

StringBuffer和StringBuilder可变字符序列

String是不可变的字符序列,涉及到字符串的改变会创建大量的对象

  1. StringBuffer :一个是线程安全的 ;效率低
  2. StringBuilder: 线程不安全的 ;效率高
  3. 共同点:
    1. 底层是采用char类型的数组存储数据,char数组默认长度是16
    2. 他们的父类都是 AbstractStringBuilder抽象类
    3. 方法相同
  4. 效率:StringBuilder>StringBuffer>>String
package string;

public class Test {
    public static void main(String[] args) {
        StringBuffer stringBuffer = new StringBuffer("HelloWorld");
        //append()在原有字符串的末尾进行追加
        StringBuffer append = stringBuffer.append(10).append(20).append(3.14);
        System.out.println(append);

        System.out.println(append.length());//18
        //指定长度
        append.setLength(60);
        System.out.println(append.length());//60
        //返回指定元素第一次出现的下标
        System.out.println(append.indexOf("l"));//2
        //返回指定元素最后一次出现的下标
        System.out.println(append.lastIndexOf("l"));//8
        //将指定元素插入到指定的位置
        append.insert(0,"你好");
        System.out.println(append);//你好HelloWorld10203.14
        //删除指定范围内元素[开始元素下标,结束元素下标)
        append.delete(0,2);
        System.out.println(append);//HelloWorld10203.14
        //删除指定位置的字符
        append.deleteCharAt(15);
        System.out.println(append);//HelloWorld1020314
        //设置指定位置字符
        append.setCharAt(0,'嘿');
        System.out.println(append);//嘿elloWorld1020314

		//方法相同
        StringBuilder stringBuilder = new StringBuilder();
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值