09 - Java String类

发布于:2024-12-07 ⋅ 阅读:(191) ⋅ 点赞:(0)

Java String 类

基本介绍

字符串广泛应用 在 Java 编程中,在 Java 中字符串属于对象,Java 提供了 String 类来创建和操作字符串。

  1. String 对象用于保存字符串,也就是一组字符序列
  2. 字符串常量对象是用 双引号括起的字符序列
  3. 字符串的字符使用 Unicode 字符编码,一个字符(不区分字母还是汉字)占两个字节
  4. String 类实现了接口 Serializable【String 可以串行化:可以在网络传输】  接口 Comparable [String 对象可以比较大小]
  5. String 是 final 类,不能被其他的类继承
  6. String 有属性 private final char value[]; 用于存放字符串内容
  7. 一定要注意:value 是一个 final 类型, 不可以修改(需要功力):即 value 不能指向新的地址,但是单个字符内容是可以变化(因为在栈区引用类型存放的是引用(堆区地址),所以不能修改地址)

创建字符串

11种构造方法‌

‌String类确实有11种构造方法‌,这些方法提供了不同的参数来初始化字符串。

以下是这些构造方法的详细列表和示例:

1.无参构造方法‌:String(),创建一个空的字符串对象。

String s = new String();

2.通过字符数组构造‌:String(char[] value),通过一个字符数组创建一个字符串。例如:

char[] chars = {'a', 'b', 'c'};

String s = new String(chars);‌

3.通过字节数组构造‌:String(byte[] bytes),通过一个字节数组创建一个字符串。例如:

byte[] bytes = {97, 98, 99};

String s = new String(bytes);‌

4.通过子字符串构造‌:String(char[] value, int offset, int count),通过一个字符数组的子数组创建一个字符串。例如:

char[] chars = {'a', 'b', 'c', 'd'};

String s = new String(chars, 1, 2); // 结果为 "bc"‌

5‌.通过字节数组的子字符串构造‌:String(byte[] bytes, int offset, int count),通过一个字节数组的子数组创建一个字符串。例如:

byte[] bytes = {97, 98, 99, 100};

String s = new String(bytes, 1, 2); // 结果为 "bc"‌

6.通过字符串构造‌:String(String original),通过一个已有的字符串创建一个新的字符串对象。例如:

String s = new String("abc");‌

7.通过字符序列构造‌:String(CharSequence s),通过一个CharSequence对象创建一个字符串。例如:

String s = new String("abc".toCharArray());‌

8‌.通过StringBuilder对象构造‌:String(StringBuilder sb),通过一个StringBuilder对象创建一个字符串。例如:

StringBuilder sb = new StringBuilder("abc");

String s = new String(sb);‌

9‌.通过StringBuffer对象构造‌:String(StringBuffer sb),通过一个StringBuffer对象创建一个字符串。例如:

StringBuffer sb = new StringBuffer("abc");

String s = new String(sb);‌

10.通过字符序列的子序列构造‌:String(CharSequence s, int start, int end),通过一个CharSequence对象的子序列创建一个字符串。例如:

String s = new String("abcdef", 1, 3); // 结果为 "bce"‌

11.通过字节序列的子序列构造‌:String(byte[] bytes, int offset, int length),通过一个字节数组的子序列创建一个字符串。例如:

byte[] bytes = {97, 98, 99, 100, 101};

String s = new String(bytes, 1, 3); // 结果为 "bce"‌

这些构造方法提供了灵活的方式来创建和初始化Java中的字符串对象,适用于不同的场景和需求。

常用的两种方法

创建字符串最简单的方式,直接赋值如下:

String str = "Hello world!";

用构造函数创建字符串:

String str = new String("Hello world!");

两者的区别

  • 方式一:直接赋值 String str = "Hello world!";,先从常量池查看是否有"Hello world!"数据空间,如果有,直接指向;如果沒有则重新创建,然后指向。str最终指向的是常量池的空间地址 。
  • 方式二:调用构造器 String str = new String("Hello world!");,先在堆中创建空间,里面维护了value属性,指向常量池的 Hello world! 空间。如果常量池没有 "Hello world!",重新创建,如果有,直接通过value指向,最终指向的是堆中的空间地址 。

常用方法

  • equals:区分大小写,判断内容是否相等
  • equalslgnoreCase:忽略大小写的判断内容是否相等
  • length:获取字符的个数,字符串的长度
  • indexOf:获取字符在字符串中第1次出现的索引,索引从0开始,如果找不到,返回-1
  • lastlndexOf:获取宇符在字符串中最后1次出现的索引,索引从0开始,如找不到,返回-1
  • substring: 截取指定范围的子串
  • trim:去前后空格
  • charAt:获取某索引处的字符,注意不能使用Str[index]这种方式
  • toUpperCase:大写字母
  • toLowerCase:小写字母
  • concat:拼接
  • replace:替换字符串中的字符
  • split:分割字符串
  • toCharArray:转换成字符数组
  • format:格式字符串
  • isEmpty:判断是否为空

equals() 方法区分大小写,判断内容是否相等

equals() 方法用于将字符串与指定的对象比较。

String 类中重写了 equals() 方法用于比较两个字符串的内容是否相等。

如果给定对象与字符串相等,则返回 true;否则返回 false。

public class Test {
    public static void main(String args[]) {
        String Str1 = new String("hello");
        String Str2 = Str1;
        String Str3 = new String("hello");
        boolean retVal;

        retVal = Str1.equals( Str2 );
        System.out.println("返回值 = " + retVal );//true

        retVal = Str1.equals( Str3 );
        System.out.println("返回值 = " + retVal );//true
    }
}

使用 == 和 equals() 比较字符串。

String 中 == 比较引用地址是否相同,equals() 比较字符串的内容是否相同:

String s1 = "Hello";              // String 直接创建
String s2 = "Hello";              // String 直接创建
String s3 = s1;                   // 相同引用
String s4 = new String("Hello");  // String 对象创建
String s5 = new String("Hello");  // String 对象创建
 
s1 == s1;         // true, 相同引用
s1 == s2;         // true, s1 和 s2 都在公共池中,引用相同
s1 == s3;         // true, s3 与 s1 引用相同
s1 == s4;         // false, 不同引用地址
s4 == s5;         // false, 堆中不同引用地址
 
s1.equals(s3);    // true, 相同内容
s1.equals(s4);    // true, 相同内容
s4.equals(s5);    // true, 相同内容

equalslgnoreCase()方法忽略大小写的判断内容是否相等

如果给定对象与字符串相等,则返回 true,否则返回 false。

equals() 会判断大小写区别,equalsIgnoreCase() 不会判断大小写区别:

public class Test {
    public static void main(String args[]) {
        String Str1 = new String("Hello");
        String Str2 = Str1;
        String Str3 = new String("Hello");
        String Str4 = new String("hello");
        boolean retVal;

        retVal = Str1.equals( Str2 );
        System.out.println("返回值 = " + retVal );//true

        retVal = Str3.equals( Str4);
        System.out.println("返回值 = " + retVal );//false

        retVal = Str1.equalsIgnoreCase( Str4 );
        System.out.println("返回值 = " + retVal );//true
    }
}

length()方法获取字符的个数,字符串的长度

空字符串的长度返回 0。

public class Test {
    public static void main(String args[]) {
        String Str1 = new String("www.baidu.com");
        String Str2 = new String("baidu" );

        System.out.print("字符串 Str1 长度 :");
        System.out.println(Str1.length());//13
        System.out.print("字符串 Str2 长度 :");
        System.out.println(Str2.length());//5
    }
}

indexOf()方法获取字符在字符串中第1次出现的索引,索引从0开始,如果找不到,返回-1

indexOf() 方法有以下四种形式:

  • public int indexOf(int ch):返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
  • public int indexOf(int ch, int fromIndex):返回从 fromIndex 位置开始查找指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
  • int indexOf(String str):返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
  • int indexOf(String str, int fromIndex):返回从 fromIndex 位置开始查找指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
public class Main {
    public static void main(String args[]) {
        String string = "aaa456ac";  
        //查找指定字符是在字符串中的下标。在则返回所在字符串下标;不在则返回-1.  
        System.out.println(string.indexOf("b")); // indexOf(String str); 返回结果:-1,"b"不存在  
 
        // 从第四个字符位置开始往后继续查找,包含当前位置  
        System.out.println(string.indexOf("a",3));//indexOf(String str, int fromIndex); 返回结果:6  
 
        //(与之前的差别:上面的参数是 String 类型,下面的参数是 int 类型)参考数据:a-97,b-98,c-99  
 
        // 从头开始查找是否存在指定的字符  
        System.out.println(string.indexOf(99));//indexOf(int ch);返回结果:7  
        System.out.println(string.indexOf('c'));//indexOf(int ch);返回结果:7  
 
        //从fromIndex查找ch,这个是字符型变量,不是字符串。字符a对应的数字就是97。  
        System.out.println(string.indexOf(97,3));//indexOf(int ch, int fromIndex); 返回结果:6  
        System.out.println(string.indexOf('a',3));//indexOf(int ch, int fromIndex); 返回结果:6  
    }
}

lastIndexOf() 获取宇符在字符串中最后1次出现的索引,索引从0开始,如找不到,返回-1

lastIndexOf() 方法有以下四种形式:

  • public int lastIndexOf(int ch):返回指定字符在此字符串中最后一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
  • public int lastIndexOf(int ch, int fromIndex):返回指定字符在此字符串中最后一次出现处的索引,从指定的索引处开始进行反向搜索,如果此字符串中没有这样的字符,则返回 -1。
  • public int lastIndexOf(String str):返回指定子字符串在此字符串中最右边出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
  • public int lastIndexOf(String str, int fromIndex):返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索,如果此字符串中没有这样的字符,则返回 -1。
public class Test {
    public static void main(String args[]) {
        String Str = new String("www.baidu.com");
        String SubStr1 = new String("baidu");
        String SubStr2 = new String("com");

        System.out.print("查找字符 o 最后出现的位置 :" );
        System.out.println(Str.lastIndexOf( 'o' ));//11
        System.out.print("从第1个位置查找字符 o 最后出现的位置 :" );//
        System.out.println(Str.lastIndexOf( 'o', 1 ));//2
        System.out.print("子字符串 SubStr1 最后出现的位置:" );
        System.out.println( Str.lastIndexOf( SubStr1 ));//4
        System.out.print("从第3个位置开始搜索子字符串 SubStr1最后出现的位置 :" );
        System.out.println( Str.lastIndexOf( SubStr1, 3 ));//4
        System.out.print("子字符串 SubStr2 最后出现的位置 :" );
        System.out.println(Str.lastIndexOf( SubStr2 ));//9
    }
}

substring()方法截取指定范围的子串

substring() 方法有以下两种形式:

  • public String substring(int beginIndex):从指定位置 beginIndex 开始,到字符串结束。
  • public String substring(int beginIndex, int endIndex):从指定位置 beginIndex 开始,到指定位置 endIndex 前一个位置结束。
public class RunoobTest {
    public static void main(String args[]) {
        String Str = new String("This is text");
 
        System.out.print("返回值 :" );
        System.out.println(Str.substring(4) );//is text
 
        System.out.print("返回值 :" );
        System.out.println(Str.substring(4, 10) );//is te
    }
}

trim()方法去前后空格

返回值:删除头尾空白符的字符串。

public class Test {
    public static void main(String args[]) {
        String Str = new String("    www.baidu.com    ");
        System.out.print("原始值 :" );//    www.baidu.com    
        System.out.println( Str );

        System.out.print("删除头尾空白 :" );//www.baidu.com
        System.out.println( Str.trim() );
    }
}

charAt()方法获取某索引处的字符,注意不能使用Str[index]这种方式

public class Test {
    public static void main(String args[]) {
        String s = "www.baidu.com";
        char result = s.charAt(6);
        System.out.println(result);//i
    }
}

toUpperCase()方法,获取大写字母

public class Test {
    public static void main(String args[]) {
        String Str = new String("www.baidu.com");

        System.out.print("返回值 :" );
        System.out.println( Str.toUpperCase());//WWW.BAIDU.COM
    }
}

toLowerCase()方法小写字母

public class Test {
    public static void main(String args[]) {
        String Str = new String("WWW.BAIDU.COM");

        System.out.print("返回值 :" );
        System.out.println( Str.toLowerCase());//www.baidu.com
    }
}

concat()方法拼接

该方法属于 String 类,使用它可以将一个字符串连接到另一个字符串的末尾。

需要注意的是,concat() 方法不会修改原字符串,而是返回一个新的字符串。

  • 如果传递给 concat() 方法的参数为 null,则会抛出 NullPointerException。
  • 如果传递给 concat() 方法的参数为空字符串 (""),则返回的字符串与调用 concat() 方法的字符串相同。
public class ConcatExample {
    public static void main(String[] args) {
        String str1 = "Hello";
        String str2 = " World";
        
        // 连接空字符串
        String result1 = str1.concat("");
        // 连接空字符串
        String result2 = str1.concat(str2);
        
        // 打印结果
        System.out.println(result1); // 输出 "Hello"
        System.out.println(result2); // 输出 "Hello World"
    }
}

replace()方法替换字符串中的字符

public String replace(char searchChar, char newChar):方法通过用 newChar 字符替换字符串中出现的所有 searchChar 字符,并返回替换后的新字符串。

public class Main {
    public static void main(String args[]) {
        String Str = new String("Hello");

        System.out.print("返回值 :" );
        System.out.println(Str.replace('o', 'T'));//HellT

        System.out.print("返回值 :" );
        System.out.println(Str.replace('l', 'D'));//HeDDo
    }
}

split()方法分割字符串

public String[] split(String regex, int limit):方法根据匹配给定的正则表达式来拆分字符串。

  • regex:正则表达式分隔符。
  • limit:分割的份数。

注意: . 、 $、 | 和 * 等转义字符,必须得加 \\。

注意:多个分隔符,可以用 | 作为连字符。

public class Test {
    public static void main(String args[]) {
        String str = new String("Welcome-to-Shenzhen");
 
        System.out.println("- 分隔符返回值 :" );
        for (String retval: str.split("-")){
            System.out.println(retval);
        }
 
        System.out.println("");
        System.out.println("- 分隔符设置分割份数返回值 :" );
        for (String retval: str.split("-", 2)){
            System.out.println(retval);
        }
 
        System.out.println("");
        String str2 = new String("www.baidu.com");
        System.out.println("转义字符返回值 :" );
        for (String retval: str2.split("\\.", 3)){
            System.out.println(retval);
        }
 
        System.out.println("");
        String str3 = new String("acount=? and uu =? or n=?");
        System.out.println("多个分隔符返回值 :" );
        for (String retval: str3.split("and|or")){
            System.out.println(retval);
        }
    }
}

#####结果#####
- 分隔符返回值 :
Welcome
to
Shenzhen

- 分隔符设置分割份数返回值 :
Welcome
to-Shenzhen

转义字符返回值 :
www
baidu
com

多个分隔符返回值 :
acount=? 
 uu =? 
 n=?

toCharArray()方法转换成字符数组

public char[] toCharArray():将字符串转换为字符数组。

public class Test {
    public static void main(String args[]) {
        String Str = new String("www.baidu.com");

        System.out.print("返回值 :" );
        System.out.println( Str.toCharArray() );//返回值 :www.baidu.com
    }
}

format() 方法创建格式化字符串

我们知道输出格式化数字可以使用 printf() 和 format() 方法。

String 类使用静态方法 format() 返回一个String 对象而不是 PrintStream 对象。

String 类的静态方法 format() 能用来创建可复用的格式化字符串,而不仅仅是用于一次打印输出。

如下所示:

System.out.printf("浮点型变量的值为 " +
                  "%f, 整型变量的值为 " +
                  " %d, 字符串变量的值为 " +
                  "is %s", floatVar, intVar, stringVar);

也可以这样写

String fs;
fs = String.format("浮点型变量的值为 " +
                   "%f, 整型变量的值为 " +
                   " %d, 字符串变量的值为 " +
                   " %s", floatVar, intVar, stringVar);

isEmpty()方法判断是否为空

public boolean isEmpty():用于判断字符串是否为空。

如果字符串为空返回 true,否则返回 false。

字符串通过 length() 方法计算字符串长度,如果返回 0,即为空字符串。

public class Main {
    public static void main(String[] args) {
        String myStr1 = "aaaa";  
        String myStr2 = "";        // 空字符串
        String myStr3 = "    ";    // 多个空格,length() 不为 0 
        System.out.println("myStr1 是否为空:" + myStr1.isEmpty());//myStr1 是否为空:false
        System.out.println("myStr2 是否为空:" + myStr2.isEmpty());//myStr2 是否为空:true
        System.out.println("myStr3 长度:" + myStr3.length());//myStr3 长度:4
        System.out.println("myStr3 是否为空:" + myStr3.isEmpty());//myStr3 是否为空:false
    }
}

String 方法

下面是 String 类支持的方法,更多详细,Java在线中文手册:https://www.matools.com/api/java8

序号

方法描述

1

char charAt(int index)

返回指定索引处的 char 值。

2

int compareTo(Object o)

把这个字符串和另一个对象比较。

3

int compareTo(String anotherString)

按字典顺序比较两个字符串。

4

int compareToIgnoreCase(String str)

按字典顺序比较两个字符串,不考虑大小写。

5

String concat(String str)

将指定字符串连接到此字符串的结尾。

6

boolean contentEquals(StringBuffer sb)

当且仅当字符串与指定的StringBuffer有相同顺序的字符时候返回真。

7

static String copyValueOf(char[] data)

返回指定数组中表示该字符序列的 String。

8

static String copyValueOf(char[] data, int offset, int count)

返回指定数组中表示该字符序列的 String。

9

boolean endsWith(String suffix)

测试此字符串是否以指定的后缀结束。

10

boolean equals(Object anObject)

将此字符串与指定的对象比较。

11

boolean equalsIgnoreCase(String anotherString)

将此 String 与另一个 String 比较,不考虑大小写。

12

byte[] getBytes()

 使用平台的默认字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。

13

byte[] getBytes(String charsetName)

使用指定的字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。

14

void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)

将字符从此字符串复制到目标字符数组。

15

int hashCode()

返回此字符串的哈希码。

16

int indexOf(int ch)

返回指定字符在此字符串中第一次出现处的索引。

17

int indexOf(int ch, int fromIndex)

返回在此字符串中第一次出现指定字符处的索引,从指定的索引开始搜索。

18

int indexOf(String str)

 返回指定子字符串在此字符串中第一次出现处的索引。

19

int indexOf(String str, int fromIndex)

返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始。

20

String intern()

 返回字符串对象的规范化表示形式。

21

int lastIndexOf(int ch)

 返回指定字符在此字符串中最后一次出现处的索引。

22

int lastIndexOf(int ch, int fromIndex)

返回指定字符在此字符串中最后一次出现处的索引,从指定的索引处开始进行反向搜索。

23

int lastIndexOf(String str)

返回指定子字符串在此字符串中最右边出现处的索引。

24

int lastIndexOf(String str, int fromIndex)

 返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索。

25

int length()

返回此字符串的长度。

26

boolean matches(String regex)

告知此字符串是否匹配给定的正则表达式。

27

boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)

测试两个字符串区域是否相等。

28

boolean regionMatches(int toffset, String other, int ooffset, int len)

测试两个字符串区域是否相等。

29

String replace(char oldChar, char newChar)

返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的。

30

String replaceAll(String regex, String replacement)

使用给定的 replacement 替换此字符串所有匹配给定的正则表达式的子字符串。

31

String replaceFirst(String regex, String replacement)

 使用给定的 replacement 替换此字符串匹配给定的正则表达式的第一个子字符串。

32

String[] split(String regex)

根据给定正则表达式的匹配拆分此字符串。

33

String[] split(String regex, int limit)

根据匹配给定的正则表达式来拆分此字符串。

34

boolean startsWith(String prefix)

测试此字符串是否以指定的前缀开始。

35

boolean startsWith(String prefix, int toffset)

测试此字符串从指定索引开始的子字符串是否以指定前缀开始。

36

CharSequence subSequence(int beginIndex, int endIndex)

 返回一个新的字符序列,它是此序列的一个子序列。

37

String substring(int beginIndex)

返回一个新的字符串,它是此字符串的一个子字符串。

38

String substring(int beginIndex, int endIndex)

返回一个新字符串,它是此字符串的一个子字符串。

39

char[] toCharArray()

将此字符串转换为一个新的字符数组。

40

String toLowerCase()

使用默认语言环境的规则将此 String 中的所有字符都转换为小写。

41

String toLowerCase(Locale locale)

 使用给定 Locale 的规则将此 String 中的所有字符都转换为小写。

42

String toString()

 返回此对象本身(它已经是一个字符串!)。

43

String toUpperCase()

使用默认语言环境的规则将此 String 中的所有字符都转换为大写。

44

String toUpperCase(Locale locale)

使用给定 Locale 的规则将此 String 中的所有字符都转换为大写。

45

String trim()

返回字符串的副本,忽略前导空白和尾部空白。

46

static String valueOf(primitive data type x)

返回给定data type类型x参数的字符串表示形式。

47

contains(CharSequence chars)

判断是否包含指定的字符系列。

48

isEmpty()

判断字符串是否为空。


网站公告

今日签到

点亮在社区的每一天
去签到