Java---String类、static关键字、Arrays类、Math类

1、String类

1.1 概念

   String 类代表字符串。Java 程序中的所有字符串字面值(如 "abc" )都作为此类的实例实现。

        也就是说,程序当中所有的双引号字符串,都是String类的对象。(就算没有new,也照样是。)

1.2字符串的特点:

  1. 字符串的内容永不可变。
  2. 因为String对象是不可变的,所以它们可以被共享
  3. 字符串效果上相当于是字符串数组,底层原理是byte[ ]。即"abc" 等效于 char[] data={ 'a' , 'b' , 'c' }

1.3创建方式

// 无参构造
String str = new String();

// 通过字符数组构造
char[] chars = {'a', 'b', 'c'};
String str2 = new String(chars);

// 通过字节数组构造
byte[] bytes = { 97, 98, 99 };
String str3 = new String(bytes);

//直接创建
String str4 = "Hello";

1.4字符常量池

程序当中直接写上双引号的字符串,就在字符常量池中。

对于基本类型来说:==是进行数值比较;

对于引用类型来说:==是进行地址值的比较。

1.5字符串的比较相关方法

有两个方法:public boolean equals(Object object):将此字符串与指定对象进行比较。

                     public boolean equalsIgnore(String str):将此字符串与指定对象进行比较,忽略大小写,只区分英文字母大小写

public class Test{
    public static void main(String[] args) {
        String str1 = "Hello";
        String str2 = "Hello";
        char[] charArray = {'H','e','l','l','o'};
        String str3 = new String(charArray);//hello

        System.out.println(str1.equals(str2));//true
        System.out.println(str2.equals(str3));//true
        System.out.println(str3.equals("Hello"));//true
        System.out.println("Hello".equals(str1));//true

        String str4 = "hello";
        System.out.println(str1.equals(str4));//false

        String str5 = "Java";
        String str6 = "java";
        //忽略大小写比较
        System.out.println(str5.equalsIgnoreCase(str6));//true
    }
}

注意事项:

  1. 任何对象都能用Object进行接收;
  2. equals方法具有对称性,也就是说a.equals(b)和b.equals(a)效果是一样的;
  3. 如果比较双方一个常量和一个变量推荐把常量字符串写在前面
 String str = null;
 System.out.println(str.equals("abc"));
//str为空,代码会抛出空指针异常NullPointException
//所以建议将常量写在前面,变量写在后面

1.6字符串的获取相关方法

常用的方法有:

public int length():获取字符串长度
public String concat(String str) :拼接字符串
public char charAt(int index):获取指定索引未知的单个字符
public int indexOf(String str):查找参数字符串在本来字符串当中出现的第一次索引位置

代码示例:

public class Demo01StringGet {
    public static void main(String[] args) {
        //获取字符串的长度
        int length = "hello".length();
        System.out.println(length);//5

        //拼接字符串
        String str1 = "Hello";
        String str2 = "World";
        String str3 = str1.concat(str2);
        System.out.println(str1);//Hello
        System.out.println(str2);//World
        System.out.println(str3);//HelloWorld  新的字符串,地址值不同

        // 获取指定索引位置的单个字符
        char ch = "Hello".charAt(2);
        System.out.println(ch);//l

        // 查找参数字符串在本来字符串当中出现的第一次索引位置
        //如果根本没有,返回-1值
        String str4 = "HelloHelloWorld";
        int index = str4.indexOf("llo");
        System.out.println(index);//2   从左往右数第一个了出现的下标为2,后边同时符合llo的形式
    }
}

1.7字符串的截取方法

常用的方法有:

public String substring(int index):截取从参数位置一直到字符串末尾,返回新字符串。

public String substring(int begin, int end):截取从begin开始,一直到end结束,中间的字符串。
备注:[begin,end),包含左边,不包含右边。

代码示例:

public class Demo01Substring {
    public static void main(String[] args) {
        String str1 = "Hello World";
        String sub = str1.substring(6);
        System.out.println(sub);//World

        String sub2 = str1.substring(6, 9);
        System.out.println(sub2);//Wor
    }
}

1.8字符串的转换方法

常用的方法:

public char[ ] toCharArray () :将此字符串转换为新的字符数组。
public byte[ ] getBytes () :使用平台的默认字符集将该 String编码转换为新的字节数组。
public String replace (CharSequence target, CharSequence replacement) :将与target匹配的字符串使用replacement字符串替换。

代码示例:

public class Demo01StringConvert {
    public static void main(String[] args) {
        // 转换成为字符数组
        char[] ch = "abc".toCharArray();
        System.out.println(ch[0]);//a
        System.out.println(ch.length);//3

        // 转换成为字节数组
        byte[] bytes = "abc".getBytes();
        for (int i = 0; i < bytes.length; i++) {
            System.out.println(bytes[i]);
        }

        // 字符串的内容替换
        String str1 = "Hello World!!!";
        String str2 = str1.replace("o","*");
        System.out.println(str2);//Hell* W*rld!!!
    }
}

1.9字符串的分割方法

常用方法:

public String[] split(String regex):按照参数的规则,将字符串切分成为若干部分。

代码示例:

public class Demo01StringSplit {
    public static void main(String[] args) {
        String str1 = "aaa,bbb,ccc";
        //按照“,”分割
        String[] array1 = str1.split(",");
        for (int i = 0; i < array1.length; i++) {
            System.out.println(array1[i]);
        }
    }
}

2、static关键字

2.1概述:

关于 static 关键字的使用,它可以用来修饰的成员变量和成员方法,被修饰的成员是属于类的,而不是单单是属于某个对象的。也就是说,既然属于类,就可以不靠创建对象来调用了

2.2修饰成员变量

如果一个成员变量使用了static关键字,那么这个变量不在属于自己,而是属于所在的类多个对象共享同一份数据

例如:

开学新生报到,现在想为每一位新来报到的同学编学号,从第一名同学开始,编号为1,以此类推。学号必须是唯一的,连续的,并且与班级的人数相符,这样以便知道,要分配给下一名新同学的学号是多少。这样我们就需要一个变量,与单独的每一个学生对象无关,而是与整个班级同学数量有关。

Student.java类

public class Student {
    private int id;//学号
    private String name;//姓名
    private int age;//年龄
    static String room;//所在教室
    private static int idCounter = 0; 类变量,记录学生数量,分配学号

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
        this.id = ++idCounter;//this当前对象的引用
    }
    public Student() {
        idCounter++;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

Demo01StaticField.java类

public class Demo01StaticField {
    public static void main(String[] args) {
        Student one = new Student("张三",20);
        one.room = "102";
        System.out.println("姓名:" + one.getName() +
                ",年龄:" + one.getAge() + ",教室:" +
                one.room + ",学号:" + one.getId());//姓名:张三,年龄:20,教室:102,学号:1

        Student two = new Student("李四",23);
        System.out.println("姓名:" + two.getName() +
                ",年龄:" + two.getAge() + ",教室:" +
                two.room + ",学号:" + two.getId());//姓名:李四,年龄:23,教室:102,学号:2

    }
}

2.3修饰成员方法

当static修饰成员方法时,该方法成为静态方法

格式:

修饰符 static 返回值类型 方法名 (参数列表){
// 执行语句
}

注意事项:

  • 如果没有static关键字,那么必须首先创建对象,然后通过对象才能使用;
  • 如果有static关键字,那么不需要创建对象,直接使用类名称来使用(类名称.静态方法());
  • 静态不能直接访问非静态(因为在内存中有的静态内容有的非静态内容
  • 静态方法当中不能使用this(this表示当前对象,通过谁调用的方法,谁就是当前对象)

代码示例:

Demo01StaticMethod.java类

public class Demo01StaticMethod {
    public static void main(String[] args) {
        //没有使用static,需要创建一个对象,才能使用该方法
        MyClass obj = new MyClass();
        obj.method();//这是一个成员方法

        //使用static,直接使用(类名称.方法名称)
        MyClass.methodStatic();//0 0 这是一个静态方法

        //使用本类当中的静态方法,可直接使用方法名称
        myMethod();//自己的方法
    }
    public static void myMethod(){
        System.out.println("自己的方法");
    }
}

 MyClass.java类

public class MyClass {
    int num;
    static int numStatic;
    public void method() {
        System.out.println("这是一个成员方法");
        System.out.println(num);
        System.out.println(numStatic);
    }

    public static void methodStatic() {
        System.out.println("这是一个静态方法");
        //静态内容不可以访问非静态内容
//        System.out.println(num);
        System.out.println(numStatic);
    }
}

2.4静态代码块

格式:

public class 类名称{
    static {
       //静态代码块的内容
    }
}

代码示例:


public class Person {
    static {
        System.out.println("静态代码执行");
    }
    public Person(){
        System.out.println("构造方法执行");
    }
}

特点:

  • 当第一次用到本类时,静态代码块执行唯一 一次。
  • 静态内容总是优先于非静态,所以静态代码块比构造方法先执行。

典型用途:

       用来一次性的对静态成员变量进行赋值。

3、Arrays类

  • java.util.Arrays 是一个与数组相关的工具类,里面提供了大量的静态方法,用来实现数组常见的操作。

常用的方法:

  • public static String toString(int[] a) :返回指定数组内容的字符串表示形式。
  • public static void sort(int[] a):对指定的 int 型数组按数字升序进行排序。

代码示例:

public class Demo01Arrays {
    public static void main(String[] args) {
        int[] intArray = {1,2,3,4};
        //数组转换为字符串
        String intStr = Arrays.toString(intArray);
        System.out.println(intStr);//[1, 2, 3, 4]

       int[] array1 = {3,5,6,2,4,9,1};
       //数组排序
       Arrays.sort(array1);
       System.out.println(Arrays.toString(array1));

       String[] array2 = {"aaa","ccc","bbb"};
       Arrays.sort(array2);
       System.out.println(Arrays.toString(array2));//[aaa, bbb, ccc]

    }
}

注意:

  1. 如果是数值,sort默认升序。
  2. 如果是字符串,sort默认按照字母升序。
  3. 如果是自定义类型,那么这个自定义的类需要有Comparable/Comparator接口的支持。

4、Math类

  • java.lang.Math 类包含用于执行基本数学运算的方法,里面提供了大量的静态方法,完成数学运算相关的操作。

常用的方法:

  • public static double abs(double a) :返回 double 值的绝对值。
  • public static double floor(double a) :返回小于等于参数最大的整数。
  • public static long round(double a) :返回最接近参数的 long。(相当于四舍五入方法)。

代码示例:

public class Demo01Math {
    public static void main(String[] args) {
        //获取绝对值
        System.out.println(Math.abs(12.22));//12.22
        System.out.println(Math.abs(-12.3));//12.3

        //向上取整
        System.out.println(Math.ceil(3.9));//4.0
        System.out.println(Math.ceil(-3.1));//-3.0
        System.out.println(Math.ceil(3.0));//3.0

        //向下取整(去零头)
        System.out.println(Math.floor(4.1));//4.0
        System.out.println(Math.floor(4.7));//4.0
        System.out.println(Math.floor(4.9));//4.0

        //四舍五入
        System.out.println(Math.round(3.14));//3
        System.out.println(Math.round(3.5));//4
        System.out.println(Math.round(3.9));//4
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用最短编辑距离算法和Java-diff-utils库来编写比对程序。最短编辑距离算法可以用来计算两个字符串之间的最小编辑操作数,而Java-diff-utils库可以帮助我们生成两个字符串之间的差异。 首先,你需要导入Java-diff-utils库到你的项目中。你可以在Maven或Gradle的配置文件中添加相应的依赖项来引入该库。 接下来,你可以使用最短编辑距离算法(例如Levenshtein距离)来计算两个字符串之间的最小编辑操作数。你可以实现一个函数来计算最小编辑距离,例如: ```java public static int calculateEditDistance(String str1, String str2) { int m = str1.length(); int n = str2.length(); int[][] dp = new int[m + 1][n + 1]; for (int i = 0; i <= m; i++) { dp[i][0] = i; } for (int j = 0; j <= n; j++) { dp[0][j] = j; } for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if (str1.charAt(i - 1) == str2.charAt(j - 1)) { dp[i][j] = dp[i - 1][j - 1]; } else { dp[i][j] = 1 + Math.min(dp[i - 1][j - 1], Math.min(dp[i][j - 1], dp[i - 1][j])); } } } return dp[m][n]; } ``` 然后,你可以使用Java-diff-utils库来生成两个字符串之间的差异。你可以实现一个函数来比较两个字符串,并返回差异结果,例如: ```java public static String compareStrings(String str1, String str2) { Patch<String> patch = DiffUtils.diff(Arrays.asList(str1.split("\\n")), Arrays.asList(str2.split("\\n"))); List<Delta<String>> deltas = patch.getDeltas(); StringBuilder result = new StringBuilder(); for (Delta<String> delta : deltas) { result.append(delta).append("\n"); } return result.toString(); } ``` 在这个例子中,我们将两个字符串按行分割,并使用Java-diff-utils库中的`DiffUtils.diff`方法来获取差异。然后,我们遍历差异列表,并将每个差异添加到结果字符串中。 请注意,这只是一个简单的示例,你可能需要根据你的实际需求进行适当的修改和调整。 希望这能帮助到你!如果你还有其他问题,请随时提问。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值