java -- String类

134 阅读7分钟

String的基本概念

  • String 类对象用于保存字符串,也就是一组字符序列。字符串常量是一组用双引号括起来的字符序列,如:“你好”,"hello"等

  • value数组是一个final类型,不可以被修改,即数组value不能再指向新的数组地址,但是数组中单个字符内容是可以改变的

final char[] value = {'a','b','c'};
char[] v2 = {'t','o','m'};
value[0] = 'H';// 可以改变数组中的元素的值
//value = v2; 错误,不可以修改 value地址
  • String类是final类,不能被其他的类继承

  • String类中有属性private final char value[],这是一个char类型的常量数组,用于存放字符串中的每一个字符

  • String 类对象与字符串常量的区别:String类对象存储在堆内存中,而字符串常量存储在方法区的常量池中;存放在常量池中的字符串常量会有一个地址,通常该地址会返回给指向该字符串常量的String 类对象的value属性;但是注意:字符串常量本身就是一个存储在常量池中的String类对象

  • 字符串的字符使用Unicode 字符编码,一个字符(无论是字母还是汉字)都占两个字节

  • String类实现了接口Serializable【说明了String类对象可以串行化:可以在网络传输】 image.png

  • String类还实现了接口Comparable【说明了String对象可以比较大小】

String 常用方法

String常见的构造方法

public String()

初始化一个新创建的String对象,使其表示一个空字符序列

String s1 = new String();
System.out.println(s1);

public String(byte[] bytes)

通过使用平台的默认字符集解码指定的byte数组,构造一个新的String

byte[] bytes={97,98,99};
String s1 = new String(bytes);
System.out.println(s1); // abc

public String(byte[] bytes,int offset,int length)

通过使用平台的默认字符集解码指定的byte子数组,构造一个新的String。

  • bytes 要解码为字符的byte
  • offest 要解码的第一个byte的索引
  • length 要解码的byte数
byte[] bytes={97,98,99};
String s2 = new String(bytes, 1, 2);
System.out.println(s2);  //bc

public String(char[] value)

把字符数组转成字符串

char[] chars={'a','b','c'};
String s3 = new String(chars);
System.out.println(s3); // abc

public String(char[] value,int index, int count)

把字符数组的一部分转成字符串

  • value 作为字符源的数组
  • index 初始偏移量
  • count 长度
char[] chars={'a','b','c'};
String s4 = new String(chars, 1, 2);
System.out.println(s4); //bc

public String(String original)

String s5="hello";
System.out.println(s5);

String常见的成员方法

public char charAt(int index)

获取指定索引对应的字符

System.out.println("abcde".charAt(1)); // b

String s = "abcde";
System.out.println(s.charAt(0));// a

public int compareTo(String anotherString)

  • 用于比较两个字符串的大小关系。

    • 如果第一个字符和参数的第一个字符不等,结束比较,返回第一个字符的ASCII码差值
    • 如果第一个字符和参数的第一个字符相等,则以第二个字符和参数的第二个字符做比较,以此类推,直至不等为止,返回该字符的ASCII码差值。
    • 如果两个字符串不一样长,可对应字符又完全一样,则返回两个字符串的长度差值
  • 返回一个整数值,表示字符串之间的比较结果。

    • 如果返回值为负数,则表示当前字符串小于被比较字符串;
    • 如果返回值为零,则表示两个字符串相等;
    • 如果返回值为正数,则表示当前字符串大于被比较字符串。
System.out.println("abcde".compareTo("abcde")); // 0
System.out.println("abcde".compareTo("c"));  // -2
System.out.println("abcde".compareTo("a"));  // 4

public String concat(String str)

字符串拼接

System.out.println("abc".concat("de")); // abcde

public String contains(String s)

判断是否包含指定的字符串

System.out.println("abcde".contains("abcde")); // true
System.out.println("abcde".contains("c"));  // true
System.out.println("abcde".contains("sud"));  // false

字母大小写

  • public String toLowerCase() 将大写字母转换成小写字母
  • public String toUpperCase() 将小写字母转换成大写字母
System.out.println("abcde".toLowerCase()); // abcde
System.out.println("ABCDE".toLowerCase());  // abcde
System.out.println("abcde".toUpperCase()); // ABCDE
System.out.println("ABCDE".toUpperCase());  // ABCDE

equals 字符串比较

  • public boolean equals(Object anObject)

比较两个字符串的内容是否一致

源码:
public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    if (anObject instanceof String) {
        String anotherString = (String)anObject;
        int n = value.length;
        if (n == anotherString.value.length) {
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = 0;
            while (n-- != 0) {
                if (v1[i] != v2[i])
                    return false;
                i++;
            }
            return true;
        }
    }
    return false;
}
System.out.println("abcde".equals("abcde")); // true
System.out.println("ABCDE".equals("abcd"));  // false
  • public boolean equalsIgnoreCase(Object anObject)

比较两个字符串的内容是否一致(不区分大小写)

System.out.println("abcde".equals("ABCDE")); // false
System.out.println("abcde".equalsIgnoreCase("ABCDE"));  // true

indexOf

public int indexOf(int ch)

获取指定字符对应的索引值,如果找不到返回-1

System.out.println("abcde".indexOf(0)); // -1
System.out.println("abcde".indexOf(1)); // -1
System.out.println("abcde".indexOf(2)); // -1
System.out.println("abcde".indexOf('a')); // 0
System.out.println("abcde".indexOf('e')); // 4

public int indexOf(String str)

获取指定字符串对应的索引值,如果找不到返回-1

System.out.println("abcde".indexOf("ab")); // 0
System.out.println("abcde".indexOf("bc")); // 1
System.out.println("abcde".indexOf("as")); // -1

public int lastIndexOf(int ch)

获取指定字符对应的最后一次出现的位置的索引

System.out.println("abcdebcdae".lastIndexOf("a")); // 8

public boolean isEmpty()

判断是否为空字符串

System.out.println("abcde".isEmpty()); // false
System.out.println("".isEmpty()); // true

public int length()

获取字符串长度

System.out.println("abcde".length()); // 5
System.out.println("".length()); // 0

前缀和后缀

public boolean startsWith(String s)

判断是否以指定的字符串为前缀的

System.out.println("abcde".startsWith("a")); // true
System.out.println("abcde".startsWith("abc")); // true
System.out.println("abcde".startsWith("bbc")); // false

public boolean endsWith(String s)

判断是否以指定的字符串为后缀的

System.out.println("abcde".endsWith("de")); // true

public byte[] getBytes()

将字符串转换成字节数组

String s = "abcde";
byte[] bys = s.getBytes();
for(int i = 0;i < bys.length; i++){
    System.out.println(bys[i]);
}

public char[] toCharArray()

将字符串转换成字符数组

String s = "abcde";
char[] chs = s.toCharArray();
for(int i = 0;i < chs.length; i++){
    System.out.println(chs[i]);
}

public String trim()

去除字符串的前后空格

System.out.println(" ab  cde  ".trim());//ab  cde

subString 截取字符串

public String subString(int beginIndex)

截取,从指定的索引开始截取到末尾

System.out.println("abcde".subString(1));//bcde

public String subString(int beginIndex,int endIndex)

截取,从指定的beginIndex索引开始截取到endIndex末尾(包头不包尾)

System.out.println("abcde".subString(0,4));//abcd

public String split(String regex)

按照指定的符号进行切割,或者,根据给定的正则表达式的匹配拆分此字符串

String s = "a-b-c-d-e";
String[] strs = s.split("-");//{"a","b","c","d","e"}
for(int i = 0; i < strs.length; i++){
    System.out.println(strs[i]);
}

replace 替换

public String replace(char oldChar,char newChar)

String s1 = "abcde";
String s2 = s1.replace('a','s');
System.out.println(s2);// sbcde
System.out.println(s1);//abcde

public String replace(String target,String replacement)

String s1 = "abcde";
String s2 = s1.replace('abc','xyz');
System.out.println(s2);// xyzde
System.out.println(s1);//abcde

String 类对象的创建方式

直接赋值

String s = “abc”;

存储过程:

  1. 首先在方法区的常量池中查看是否存在一个存储了 “abc” 的空间;

  2. 如果存在,就在栈空间中声明一个对象名 s ,然后将该空间的地址返回给 s ,s 最终指向的是常量池的空间地址(说明 s 是可变的,同时该字符串常量也是一个对象;

  3. 如果不存在,就在常量池中开辟一个空间,将 “abc” 存储进去,然后在栈空间中声明一个对象名 s ,再将该空间的地址返回给 s ,s 最终指向的是常量池的空间地址(说明 s 是可变的),同时该字符串常量也是一个对象。

调用构造器

String s2 = new String(“abc”);

存储过程:

  1. 首先在堆内存中开辟了一个空间,这个空间是真正的String 类对象,该空间里面存在一个char 数组类型的 value 属性,value 指向了常量池;

  2. 接着String 类对象在方法区的常量池中查看是否存在一个存储了 “abc” 的空间;

  3. 如果存在,就将该空间的地址返回给 value ,value 最终指向的是常量池的空间地址;(注意:value 是 final 类型的)

  4. 如果不存在,就在常量池中开辟一个空间,将 “lineryue” 存储进去,再将该空间的地址返回给 value ,value 最终指向的是常量池的空间地址;

  5. 最后,在栈内存中声明一个对象名 s2 ,将堆内存中 String 类对象空间的地址返回给 s2 ,s2 最终指向的是堆空间中的String 类对象地址。 image.png

String类常见题目

题目一:

String s1 = "abc";
String s2 = "bc";
String s3 = s2 + "d";
/*
    StringBuffer sb = new StringBuffer();
    sb.append(s2);
    sb.append("c");
    String s3 = sb.toString();
*/
System.out.println(s1 == s3);

image.png

题目二:

常量优化机制

String s1 = "abc";
String s2 = "ab" + "c"; // 由于常量优化机制,相当于String s2 = "abc"
System.out.println(s1 == s2);// true