String类—javaSE

文章目录

  • 1.常用方法
    • 1.1字符串构造
    • 1.2String对象的比较
    • 1.3字符串查找
    • 1.4转化
    • 1.5字符串替换
    • 1.6字符串拆分
    • 1.7字符串的截取
    • 1.8去掉字符串中的左右空格,保留中间空格
  • 2.字符串常量池
    • 2.1 直接使用字符串常量进行赋值
    • 2.2通过new创建String类对象
    • 2.3 intern方法
    • 2.4String类中两种对象实例化的区别
  • 3.字符串的不可变性
  • 4.字符串的修改
  • 5.StringBuilder和StringBuffer
    • 5.1StringBuilder
    • 5.2String、StringBuffer、StringBuilder的区别
  • 6.习题
    • 6.1 以下总共创建了多少个String对象
    • 6.2字符串中的第一个唯一字符
    • 6.3字符串最后一个单词的长度
    • 6.4验证字符串是否是回文串

1.常用方法

1.1字符串构造

(1)常用的三种方式

public class TextDame {
    public static void main(String[] args) {
        //使用常量串构造
        String str1 = "hello";
        //直接newString对象
        String str2 = new String("hello");
        //使用字符数组进行构造
        char[] ch = {'h','e','l','l','o'};
        String str3 = new String(ch);
    }
}

(2)String是引用类型,内部并不存储字符串本身,在jdk1.8中,字符串实际保存在char类型的数组中
String类—javaSE_第1张图片

(3)在Java中“”引起来的也是String类型对象

public class TextDame {
    public static void main(String[] args) {
        String str1 = new String("hello");
        String str2 = new String("hello");
        String str3 = str1;
        System.out.println(str1 == str2);//false
        System.out.println(str1 == str3);//true
        System.out.println(str1.length());//5
        System.out.println("hello".length());//5
    }
}

1.2String对象的比较

(1)== 比较是否引用同一个对象(对于简单类型,==比较的是变量中的值;对于引用类型 ==比较的是引用中的地址)

public class TextDame {
    public static void main(String[] args) {
        String s1 = new String("hello");
        String s2 = new String("hello");
        String s3 = new String("world");
        String s4 = s1;
        System.out.println(s1 == s2); // false
        System.out.println(s2 == s3); // false
        System.out.println(s1 == s4); // true

    }
}

(2)equals:比较内容是否相同

public class TextDame {
    public static void main(String[] args) {
        String s1 = new String("hello");
        String s2 = new String("hello");
        // s1、s2引用的是三个不同对象,因此==比较结果全部为false
        System.out.println(s1 == s2); // false
        // 虽然s1与s2引用的不是同一个对象,但是两个对象中放置的内容相同,因此输出true
        System.out.println(s1.equals(s2)); // true
    }
}

(3)compareTo方法是按照字典序进行比较,compareTo返回的是int类型,具体比较方式:先按照字典次序大小比较,如果出现不等的字符,直接返回这两个字符的大小差值; 如果前k个字符相等(k为两个字符长度最小值),返回值两个字符串长度差值

public class TextDame {
    public static void main(String[] args) {
        String s1 = new String("ac");
        String s2 = new String("abc");
        String s3 = new String("ac");
        String s4 = new String("acdef");
        System.out.println(s1.compareTo(s2));//s1 > s2,输出正数
        System.out.println(s1.compareTo(s3));//s1 == s3,输出0
        System.out.println(s1.compareTo(s4));//s1 
    }
}

(4)compareToIgnoreCase方法:与compareTo方式相同,但是忽略大小写比较

public class TextDame {
    public static void main(String[] args) {
        String s1 = new String("aBc");
        String s2 = new String("abc");
        System.out.println(s1.compareToIgnoreCase(s2));//0
    }
}

1.3字符串查找

package dame3;

public class TextDame {
    public static void main(String[] args) {
        String s = "aabcabcaabc";
        System.out.println(s.charAt(3)); // c,返回3号下标对应的字符
        System.out.println(s.indexOf('c')); // 3,返回第一个c出现的下标
        System.out.println(s.indexOf('c', 1)); // 3,从1号下标开始找,返回第一个出现c的下标
        System.out.println(s.indexOf("abc")); // 1,返回第一个abc出现a的下标
        System.out.println(s.indexOf("abc", 1)); // 1,从1号下标开始找,返回第一个abc出现a的下标
        System.out.println(s.lastIndexOf('c')); // 10,从后往前找第一个出现c的下标
        System.out.println(s.lastIndexOf('a', 10)); // 8,从10号下标开始找,从后往前找第一个出现a的下标
        System.out.println(s.lastIndexOf("abc")); // 8,从后往前找返回第一个abc出现a的下标
        System.out.println(s.lastIndexOf("abc", 10)); // 8,从10号下标开始找,从后往前找返回第一个abc出现a的下标
    }
}

1.4转化

(1)数值和字符串转化

public class TextDame {
    public static void main(String[] args) {
        //数字转化为字符串
        String str1 = String.valueOf(12);
        String str2 = String.valueOf(12.3);
        //字符串转化为数字
        int a = Integer.parseInt("12");
        Double b = Double.parseDouble("12.3");
    }
}

(2)字符串大小写转换

public class TextDame {
    public static void main(String[] args) {
        String str1 = "abCDeF";
        String str2 = str1.toLowerCase();//大写转小写
        String str3 = str1.toUpperCase();//小写转大写
        System.out.println(str2);//abcdef
        System.out.println(str3);//ABCDEF
    }
}

(3)字符串和数组转化

public class TextDame {
    public static void main(String[] args) {
        String str1 = "hello";
        //字符串转数组
        char[] ch = str1.toCharArray();
        for (int i = 0; i < ch.length; i++) {
            System.out.print(ch[i] + " ");
        }
        System.out.println();
        //数组转字符串
        String str2 = new String(ch);
        System.out.println(ch);
    }
}

(4)格式化

public class TextDame {
    public static void main(String[] args) {
        String str1 = String.format("%d-%d-%d",2023,6,19);
        System.out.println(str1);//2023-6-19
    }
}

1.5字符串替换

注意:由于字符串是不可变对象, 替换不修改当前字符串, 而是产生一个新的字符串

public class TextDame {
    public static void main(String[] args) {
        String str1 = "hello,world";
        String ret = str1.replaceAll("l","g");//将所有的l替换为g
        System.out.println(ret);//heggo,worgd
        String ret1 = str1.replaceFirst("l","c");//将第一个l替换为c
        System.out.println(ret1);//heclo,world
    }
}

1.6字符串拆分

public class TextDame {
    public static void main(String[] args) {
        String str1 = "hello,world,hello,hello,world,hello";
        String[] str = str1.split(",");//将字符串按逗号分开,存放在字符串数组中
        for (String s: str) {
            System.out.print(s + " ");//hello world hello hello world hello 
        }
        System.out.println();
        String[] str2 = str1.split(",",2);//将字符串按逗号分开,第二个参数是限制分组的组数,存放在字符串数组中
        for (String s: str2) {
            System.out.print(s + " ");//hello world,hello,hello,world,hello 
        }
    }
}

1.7字符串的截取

public class TextDame {
    public static void main(String[] args) {
        String str1 = "hello,world";
        String str = str1.substring(3);//从指定位置开始截取
        System.out.println(str);//lo,world
        String str2 = str1.substring(3,5);//截取从起始位置到终止位置,左闭右开
        System.out.println(str2);//lo
    }
}

1.8去掉字符串中的左右空格,保留中间空格

public class TextDame {
    public static void main(String[] args) {
        String str1 = "   hello world hello hello world hello  ";
        String str = str1.trim();
        System.out.println(str);//hello world hello hello world hello
    }
}

2.字符串常量池

(1)为了使程序的运行速度更快、更节省内存,Java为8种基本数据类型和String类都提供了常量池
(2)字符串常量池在JVM中是StringTable类,实际是一个固定大小的HashTable

  1. 在JVM中字符串常量池只有一份,是全局共享的
  2. 刚开始字符串常量池是空的,随着程序不断运行,字符串常量池中元素会越来越多
  3. 当类加载时,字节码文件中的常量池也被加载到JVM中,称为运行时常量池,同时会将其中的字符串常量保存在字符串常量池中
  4. 字符创常量池中的内容:一部分来自运行时常量池,一部分来自程序动态添加

2.1 直接使用字符串常量进行赋值

public class TextDame {
    public static void main(String[] args) {
        String s1 = "hello";
        String s2 = "hello";
        System.out.println(s1 == s2); // true
    }
}

String类—javaSE_第2张图片

2.2通过new创建String类对象

public class TextDame {
    public static void main(String[] args) {
        String s1 = new String("hello");
        String s2 = new String("hello");
        System.out.println(s1 == s2); // false
    }
}

String类—javaSE_第3张图片

2.3 intern方法

该方法的作用是手动将创建的String对象添加到常量池中

public class TextDame {
    public static void main(String[] args) {
        char[] ch = new char[]{'a', 'b', 'c'};
        String s1 = new String(ch); // s1对象并不在常量池中
        s1.intern(); // 调用之后,会将s1对象的引用放入到常量池中
        String s2 = "abc"; // "abc" 在常量池中存在了,s2创建时直接用常量池中"abc"的引用
        System.out.println(s1 == s2);//true
    }
}

2.4String类中两种对象实例化的区别

(1)String str = “hello”:只会开辟一块堆内存空间,保存在字符串常量池中,然后str共享常量池中的String对象
(2)String str = new String(“hello”):会开辟两块堆内存空间,字符串"hello"保存在字符串常量池中,然后用常量池中的String对象给新开辟的String对象赋值
(3) String str = new String(new char[]{‘h’, ‘e’, ‘l’, ‘l’, ‘o’}):现在堆上创建一个String对象,然后利用copyof将重新开辟数组空间,将参数字符串数组中内容拷贝到String对象中

3.字符串的不可变性

(1)String类在设计时就是不可改变的,String类实现描述中已经说明了
String类—javaSE_第4张图片
String类中的字符实际保存在内部维护的value字符数组中,String类被final修饰,表明该类不能被继承,value被修饰被final修饰,表明value自身的值不能改变,即不能引用其它字符数组,但是其引用空间中的内容可以修改
(2)所有涉及到可能修改字符串内容的操作都是创建一个新对象,改变的是新对象。final修饰类表明该类不想被继承,final修饰引用类型表明该引用变量不能引用其他对象,但是其引用对象中的内容是可以修改的

public class TextDame {
    public static void main(String[] args) {
        final int[] array = new int[]{1,2,3,4};
        array[0] = 100;
        System.out.println(Arrays.toString(array));//[100, 2, 3, 4]
    }
}

4.字符串的修改

(1)尽量避免直接对String类型对象进行修改,因为String类是不能修改的,所有的修改都会创建新对象,效率非常低
(2)String的拼接底层会被优化为StringBuilder对象的拼接,使用的是append,如下述代码中的一行代码会被优化为四行代码,进行拼接的时候会创建新的对象,因此对于String对象进行修改的时候建议使用stringbuffer或者stringbuilder
String类—javaSE_第5张图片

5.StringBuilder和StringBuffer

5.1StringBuilder

(1)String和StringBuilder类不能直接转换
(2)转换原则:String变为StringBuilder是利用StringBuilder的构造方法或append()方法;StringBuilder变为String是调用toString()方法

public class TextDame {
    public static void main(String[] args) {
        StringBuilder sb1 = new StringBuilder("hello");
        StringBuilder sb2 = sb1;
        // append:追加字符、字符串、整形数字
        sb1.append(',');
        sb1.append("world");
        sb1.append(123);
        System.out.println(sb1); // hello,world123
        System.out.println(sb1 == sb2); // true
        System.out.println(sb1.charAt(0)); // 获取0号位上的字符 h
        System.out.println(sb1.length()); // 获取字符串的有效长度 14
        System.out.println(sb1.capacity()); //获取底层数组的总大小 21
        sb1.setCharAt(0, 'H'); // 设置任意位置的字符
        sb1.insert(0, "Hello world!!!"); //在任意位置添加字符或字符串
        System.out.println(sb1);//Hello world!!!Hello,world123
        System.out.println(sb1.indexOf("Hello")); //获取Hello第一次出现的位置 0
        System.out.println(sb1.lastIndexOf("Hello")); //获取hello最后一次出现的位置 14
        sb1.deleteCharAt(0); //删除首字符
        System.out.println(sb1);//ello world!!!Hello,world123
        sb1.delete(0,5); // 删除[0, 5)范围内的字符
        System.out.println(sb1);//world!!!Hello,world123
        String str = sb1.substring(0, 5); // 截取[0, 5)区间中的字符以String的方式返回
        System.out.println(str);//world
        System.out.println(sb1);//world!!!Hello,world123
        sb1.reverse(); // 字符串逆转
        str = sb1.toString(); // 将StringBuffer以String的方式返回
        System.out.println(str);//321dlrow,olleH!!!dlrow
    }
}

5.2String、StringBuffer、StringBuilder的区别

  1. String的内容不可修改,StringBuffer与StringBuilder的内容可以修改
  2. StringBuffer与StringBuilder大部分功能是相似的
  3. StringBuffer采用同步处理,属于线程安全操作;而StringBuilder未采用同步处理,属于线程不安全操作

6.习题

6.1 以下总共创建了多少个String对象

String str = new String("ab"); // 两个("ab"和new String)
String str = new String("a") + new String("b"); // 六个("a","b",new String,new String,StringBuilder,toString)

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

解法一:数组

class Solution {
    public int firstUniqChar(String s) {
        if(s == null){
            return -1;
        }
        int[] arr = new int[26];
        for(int i = 0;i < s.length();i++){
            arr[s.charAt(i) - 'a']++;
        }
        for(int i = 0;i < s.length();i++){
            if(arr[s.charAt(i) - 'a'] == 1){
                return i;
            }
        }
        return -1;
    }
}

解法二:HashMap

class Solution {
    public int firstUniqChar(String s) {
        if(s == null || s.length() == 0){
            return -1;
        }
        HashMap<Character,Integer> map = new HashMap<>();
        for(int i = 0; i < s.length();i++){
            if(map.containsKey(s.charAt(i))){
                map.put(s.charAt(i),map.get(s.charAt(i)) + 1);
            }else{
                map.put(s.charAt(i),1);
            }
        }
        for(int i = 0;i < s.length();i++){
            if(map.get(s.charAt(i)) == 1){
                return i;
            }
        }
        return -1;
    }
}

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

import java.util.Scanner;
public class Main {
    public static int stringLength(String str){
        if(str == null || str.length() == 0){
            return -1;
        }
        // 找到最后一个空格出现的位置,返回最后一个空格所在位置的下标
        int index = str.lastIndexOf(" ");
        return str.length() - index - 1;
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) { 
            String str = sc.nextLine();
            int ret = stringLength(str);
            System.out.println(ret);
        }
    }
}

6.4验证字符串是否是回文串

class Solution {
    // 判断该字符是不是字母或数字
    public static boolean isCharacterOrNumber(char ch){
        if(ch >= '0' && ch <= '9' || ch >= 'a' && ch <= 'z'){
            return true;
        }
        return false;
    }
    public boolean isPalindrome(String s) {
        if(s == null || s.length() == 0){
            return true;
        }
        // 将字符串全部转化为小写字符
        s = s.toLowerCase();
        int left = 0;
        int right = s.length() - 1;
        while(left < right){
            // 在左边找到字母或数字的字符
            while(left < right && !isCharacterOrNumber(s.charAt(left))){
                left++;
            }
            // 在右边找到字母或数字的字符
            while(left < right && !isCharacterOrNumber(s.charAt(right))){
                right--;
            }
            // 如果当前对应位置上的字符不相等就返回false
            if(s.charAt(left) != s.charAt(right)){
                return false;
            }
            left++;
            right--;
        }
        return true;
    }
}

你可能感兴趣的:(Java,java,开发语言)