likes
comments
collection
share

Java的String 类

作者站长头像
站长
· 阅读数 19

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

创建字符串

在代码中遇到字符串常量时,这里的值是 "Runoob",编译器会使用该值创建一个 String 对象。创建字符串最简单的方式如下:

String str = "Runoob";

和其它对象一样,可以使用关键字和构造方法来创建 String 对象。例如用构造函数创建字符串:

String str2=new String("Runoob");

String 类有 11 种构造方法,这些方法提供不同的参数来初始化字符串,比如提供一个字符数组参数:

public class StringDemo{
   public static void main(String args[]){
      char[] helloArray = { 'r', 'u', 'n', 'o', 'o', 'b'};
      String helloString = new String(helloArray);  
      System.out.println( helloString );
   }
}
// 例编译运行结果如下:
// runoob

两种方式创建字符串的区别:String 创建的字符串存储在公共池中,而 new 创建的字符串对象在堆上:

String s1 = "Runoob";              // String 直接创建
String s2 = "Runoob";              // String 直接创建
String s3 = s1;                    // 相同引用
String s4 = new String("Runoob");   // String 对象创建
String s5 = new String("Runoob");   // String 对象创建

Java的String 类

注意:String 类是不可改变的,所以你一旦创建了 String 对象,那它的值就无法改变了。如果需要对字符串做很多修改,那么应该选择使用StringBuffer & StringBuilder 类。例如:

String s = "Google";
System.out.println("s = " + s);

s = "Runoob";
System.out.println("s = " + s);

// 输出结果为:
// Google
// Runoob

从结果上看是改变了,但为什么说 String 对象是不可变的呢?原因在于实例中的 s 只是一个 String 对象的引用,并不是对象本身,当执行 s = "Runoob"; 创建了一个新的对象 "Runoob",而原来的 "Google" 还存在于内存中。

Java的String 类

字符串长度

用于获取有关对象的信息的方法称为访问器方法。String 类的一个访问器方法是 length() 方法,它返回字符串对象包含的字符数。下面的代码执行后,len 变量等于 14:

public class StringDemo {
    public static void main(String args[]) {
        String site = "www.juejin.cn";
        int len = site.length();
        System.out.println( "掘金网址长度 : " + len );
   }
}
// 以上实例编译运行结果如下:
// 掘金网址长度 : 13

连接字符串

String 类提供了连接两个字符串的方法,该方法返回 string2 连接 string1 的新字符串:

string1.concat(string2);

也可以对字符串常量使用 concat() 方法,如:

"我的名字是 ".concat("Runoob");

更常用的是使用'+'操作符来连接字符串,如:

"Hello," + " runoob" + "!"

创建格式化字符串

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

输出格式化字符串:

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

String 类使用静态方法 format() 用来创建并返回可复用的格式化字符串:

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

String 方法

SN(序号)方法描述
1char charAt(int index),返回指定索引处的 char 值
2int compareTo(String anotherString),按字典顺序比较两个字符串
3int compareToIgnoreCase(String str),按字典顺序比较两个字符串,不考虑大小写
4String concat(String str),将指定字符串连接到此字符串的结尾
5boolean contentEquals(StringBuffer sb),当且仅当字符串与指定的StringBuffer有相同顺序的字符时候返回真
6static String copyValueOf(char[] data),返回指定数组中表示该字符序列的 String
7static String copyValueOf(char[] data, int offset, int count),返回指定数组中表示该字符序列的 String
8boolean endsWith(String suffix),测试此字符串是否以指定的后缀结束
9boolean equals(Object anObject),将此字符串与指定的对象比较
10boolean equalsIgnoreCase(String anotherString),将此 String 与另一个 String 比较,不考虑大小写
11byte[] getBytes(),使用平台的默认字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中
12byte[] getBytes(String charsetName),使用指定的字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中
13void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin),将字符从此字符串复制到目标字符数组
14int hashCode(),返回此字符串的哈希码
15int indexOf(int ch),返回指定字符在此字符串中第一次出现处的索引
16int indexOf(int ch, int fromIndex),返回在此字符串中第一次出现指定字符处的索引,从指定的索引开始搜索
17int indexOf(String str),返回指定子字符串在此字符串中第一次出现处的索引
18int indexOf(String str, int fromIndex),返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始
19String intern(),返回字符串对象的规范化表示形式
20int lastIndexOf(int ch),返回指定字符在此字符串中最后一次出现处的索引
21int lastIndexOf(int ch, int fromIndex),返回指定字符在此字符串中最后一次出现处的索引,从指定的索引处开始进行反向搜索
22int lastIndexOf(String str),返回指定子字符串在此字符串中最后一次出现处的索引
23int lastIndexOf(String str, int fromIndex),返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索
24int length(),返回此字符串的长度
25boolean matches(String regex),告知此字符串是否匹配给定的正则表达式
26boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len),测试两个字符串区域是否相等
27boolean regionMatches(int toffset, String other, int ooffset, int len),测试两个字符串区域是否相等
28String replace(char oldChar, char newChar),返回一个新的字符串,新的字符串是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的
29String replaceAll(String regex, String replacement),使用给定的 replacement 替换此字符串所有匹配给定的正则表达式的子字符串
30String replaceFirst(String regex, String replacement),使用给定的 replacement 替换此字符串匹配给定的正则表达式的第一个子字符串
31String[] split(String regex),根据给定正则表达式的匹配拆分此字符串
32String[] split(String regex, int limit),根据匹配给定的正则表达式来拆分此字符串
33boolean startsWith(String prefix),测试此字符串是否以指定的前缀开始
34boolean startsWith(String prefix, int toffset),测试此字符串从指定索引开始的子字符串是否以指定前缀开始
35CharSequence subSequence(int beginIndex, int endIndex),返回一个新的字符序列,它是此序列的一个子序列
36String substring(int beginIndex),返回一个新的字符串,它是此字符串的一个子字符串
37String substring(int beginIndex, int endIndex),返回一个新的字符串,它是此字符串的一个子字符串
38char[] toCharArray(),将此字符串转换为一个新的字符数组
49String toLowerCase(),使用默认语言环境的规则将此 String 中的所有字符都转换为小写
40String toLowerCase(Locale locale),使用给定 Locale 的规则将此 String 中的所有字符都转换为小写
41String toString(),返回此对象本身(它已经是一个字符串!)
42String toUpperCase(),使用默认语言环境的规则将此 String 中的所有字符都转换为大写
43String toUpperCase(Locale locale),使用给定 Locale 的规则将此 String 中的所有字符都转换为大写
44String trim(),返回字符串的副本,忽略前导空白和尾部空白
45static String valueOf(primitive data type x),返回给定data type类型x参数的字符串表示形式
46contains(CharSequence chars),判断是否包含指定的字符系列
47isEmpty() ,判断字符串是否为空

方法实例:\color{red}{方法实例:}方法实例:

charAt() 方法实例

public char charAt(int index)

描述

charAt() 方法用于返回指定索引处的字符。索引范围为从 0 到 length() - 1。

参数

  • index -- 字符的索引。

返回值

返回指定索引处的字符。

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

// 以上程序执行结果为:
// e

compareTo() 方法实例

public int compareTo(String anotherString)

描述

compareTo() 方法按字典顺序比较两个字符串。

参数

  • anotherString -- 要比较的字符串。

返回值

  • 如果第一个字符和参数的第一个字符不等,结束比较,返回第一个字符的ASCII码差值。
  • 如果第一个字符和参数的第一个字符相等,则以第二个字符和参数的第二个字符做比较,以此类推,直至不等为止,返回该字符的ASCII码差值。
  • 如果两个字符串不一样长,可对应字符又完全一样,则返回两个字符串的长度差值。
public class Test {
    public static void main(String[] args) {
        String str1 = "Strings";
        String str2 = "Strings";
        String str3 = "Strings123";

        int result = str1.compareTo( str2 );
        System.out.println(result);

        result = str2.compareTo( str3 );
        System.out.println(result);

        result = str3.compareTo( str1 );
        System.out.println(result);
    }
}

// 以上程序执行结果为:
// 0
// -3
// 3

compareToIgnoreCase() 方法实例

public int compareToIgnoreCase(String str)

描述

compareToIgnoreCase() 方法用于按字典顺序比较两个字符串,不考虑大小写。

参数

  • str -- 要比较的字符串。

返回值

  • 如果第一个字符和参数的第一个字符不等,结束比较,返回第一个字符的ASCII码差值。
  • 如果第一个字符和参数的第一个字符相等,则以第二个字符和参数的第二个字符做比较,以此类推,直至不等为止,返回该字符的ASCII码差值。
  • 如果两个字符串不一样长,可对应字符又完全一样,则返回两个字符串的长度差值。
public class Test {
    public static void main(String[] args) {
        String str1 = "STRINGS";
        String str2 = "Strings";
        String str3 = "Strings123";

        int result = str1.compareToIgnoreCase( str2 );
        System.out.println(result);

        result = str2.compareToIgnoreCase( str3 );
        System.out.println(result);

        result = str3.compareToIgnoreCase( str1 );
        System.out.println(result);
    }
}

// 以上程序执行结果为:
// 0
// -3
// 3

concat() 方法实例

public String concat(String str)

描述

concat() 方法用于将指定的字符串参数连接到字符串上。

参数

  • s -- 要连接的字符串。

返回值

返回连接后的新字符串。

public class Test {
    public static void main(String[] args) {
        String s = "稀土掘金:";
        s = s.concat("www.juejin.cn");
        System.out.println(s);
    }
}

// 以上程序执行结果为:
// 稀土掘金:www.juejin.cn

contentEquals() 方法实例

public boolean contentEquals(StringBuffer sb)

描述

contentEquals() 方法用于将此字符串与指定的 StringBuffer 比较。

参数

  • sb -- 要与字符串比较的 StringBuffer。

返回值

如字符串与指定 StringBuffer 表示相同的字符序列,则返回 true;否则返回 false。

public class Test {
    public static void main(String[] args) {
        String str1 = "String1";
        String str2 = "String2";
        StringBuffer str3 = new StringBuffer( "String1");

        boolean  result = str1.contentEquals( str3 );
        System.out.println(result);

        result = str2.contentEquals( str3 );
        System.out.println(result);
    }
}

// 以上程序执行结果为:
// true
// false

copyValueOf() 方法实例

// 该方法有以下几种语法格式:
public static String copyValueOf(char data[]) 
public static String copyValueOf(char data[], int offset, int count) 

描述

Java 中的 copyValueOf(char[] data) 是 String 类的一个静态方法,它将指定字符数组中的所有字符复制到一个新的字符数组中,并返回一个新的字符串。该方法与 String 类中的 valueOf(char[] data) 方法非常相似,但它将返回一个新的字符数组,而不是使用输入数组中的字符创建一个新的字符串对象。copyValueOf(char[] data) 方法有两个重载形式,其中一个允许指定要从输入数组中复制的起始位置和要复制的字符数。

参数

  • data -- 字符数组。
  • offset -- 子数组的初始偏移量。。
  • count -- 子数组的长度。

返回值

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

注意

offset 和 count 参数的值不能超出输入字符数组的边界,否则将抛出 ArrayIndexOutOfBoundsException 异常。

public class Test {
    public static void main(String[] args) {
        char[] Str1 = {'h', 'e', 'l', 'l', 'o', ' ', 'j', 'u', 'e', 'j', 'i', 'n'};
        String Str2 = "";

        // 使用整个输入字符数组来创建一个新的字符串对象。
        Str2 = Str2.copyValueOf( Str1 );
        System.out.println("返回结果:" + Str2);

        // 从输入字符数组的第 3 个字符(即偏移量为 2)开始,复制 6 个字符,并创建一个新的字符串对象。
        Str2 = Str2.copyValueOf( Str1, 2, 6 );
        System.out.println("返回结果:" + Str2);
    }
}

// 以上程序执行结果为:
// 返回结果:hello juejin
// 返回结果:llo ju

endsWith() 方法实例

public boolean endsWith(String suffix)

描述

endsWith() 方法用于测试字符串是否以指定的后缀结束。

参数

  • suffix -- 指定的后缀。

返回值

如果参数表示的字符序列是此对象表示的字符序列的后缀,则返回 true;否则返回 false。

注意

如果参数是空字符串,或者等于此 String 对象(用 equals(Object) 方法确定),则结果为 true。

public class Test {
    public static void main(String[] args) {
        String Str = new String("稀土掘金:www.juejin.cn");
        boolean retVal;

        retVal = Str.endsWith( "juejin" );
        System.out.println("返回值 = " + retVal );

        retVal = Str.endsWith( "cn" );
        System.out.println("返回值 = " + retVal );
    }
}

// 以上程序执行结果为:
// 返回值 = false
// 返回值 = true

equals() 方法实例

public boolean equals(Object anObject)

描述

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

参数

anObject -- 与字符串进行比较的对象。

返回值

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

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

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

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

// 以上程序执行结果为:
// 返回值 = true
// 返回值 = true

equalsIgnoreCase() 方法实例

public boolean equalsIgnoreCase(String anotherString)

描述

equalsIgnoreCase() 方法用于将字符串与指定的对象比较,不考虑大小写。

参数

anotherString -- 与调用方字符串进行比较的字符串对象。

返回值

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

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

        // 比较内容,考虑大小写
        retVal = Str1.equals( Str3 );
        System.out.println("返回值 = " + retVal );

        // 比较内容,不考虑大小写
        retVal = Str1.equalsIgnoreCase( Str3 );
        System.out.println("返回值 = " + retVal );
    }
}

// 以上程序执行结果为:
// 返回值 = false
// 返回值 = true

getBytes() 方法实例

// 该方法有以下几种语法格式:
public byte[] getBytes()
public byte[] getBytes(String charsetName)

描述

getBytes()方法有两个重载形式

  • 一种使用平台的默认字符集将字符串编码为 byte 序列,并将结果存储到一个新的 byte 数组中。
  • 另外一种使用指定的字符集将字符串编码为 byte 序列,并将结果存储到一个新的 byte 数组中。

参数

  • charsetName:支持的字符集名称。

返回值

返回 byte 数组。

public class Test {
    public static void main(String[] args) {
        String Str1 = new String("junjin");

        try{
            byte[] Str2 = Str1.getBytes();
            System.out.println("返回值:" + Str2 );

            Str2 = Str1.getBytes( "UTF-8" );
            System.out.println("返回值:" + Str2 );

            Str2 = Str1.getBytes( "ISO-8859-1" );
            System.out.println("返回值:" + Str2 );
        } catch ( UnsupportedEncodingException e){
            System.out.println("不支持的字符集");
        }
    }
}

// 以上程序执行结果为:
// 返回值:[B@29453f44
// 返回值:[B@5cad8086
// 返回值:[B@6e0be858

getChars() 方法实例

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

描述

getChars() 方法将字符从字符串复制到目标字符数组。

参数

  • srcBegin -- 字符串中要复制的第一个字符的索引。
  • srcEnd -- 字符串中要复制的最后一个字符之后的索引。
  • dst -- 目标数组。
  • dstBegin -- 目标数组中的起始偏移量。

返回值

没有返回值,但会抛出 IndexOutOfBoundsException 异常。

public class Test {
    public static void main(String[] args) {
        String Str1 = new String("www.juejin.cn");
        char[] Str2 = new char[6];

        try {
            Str1.getChars(4, 10, Str2, 0);
            System.out.print("拷贝的字符串为:" );
            System.out.println(Str2 );
        } catch( Exception ex) {
            System.out.println("触发异常...");
        }
    }
}

// 以上程序执行结果为:
// 拷贝的字符串为:juejin

hashCode() 方法实例

public int hashCode()

描述

hashCode() 方法用于返回字符串的哈希码。字符串对象的哈希码根据以下公式计算:

// 使用 int 算法,这里 s[i] 是字符串的第 i 个字符的 ASCII 码,
// n 是字符串的长度,
// ^ 表示求幂。
// 空字符串的哈希值为 0。
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]

参数

返回值

返回对象的哈希码值。

public class Test {
    public static void main(String[] args) {
        String Str = new String("www.juejin.cn");
        System.out.println("字符串的哈希码为 :" + Str.hashCode() );
    }
}

// 以上程序执行结果为:
// 字符串的哈希码为 :99498253

indexOf() 方法实例

// 该方法有以下几种语法格式:
public int indexOf(int ch)
public int indexOf(int ch, int fromIndex) 
public int indexOf(String str)
public int indexOf(String str, int fromIndex) 

描述

indexOf()方法有四个重载形式

  • 返回指定 字符 在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
  • 返回从 fromIndex 位置开始查找指定 字符 在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
  • 返回指定 子字符串 在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
  • 返回从 fromIndex 位置开始查找指定 子字符串 在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。

参数

  • ch -- 字符,Unicode 编码。
  • fromIndex -- 开始搜索的索引位置,第一个字符是 0 ,第二个是 1 ,以此类推。
  • str -- 要搜索的子字符串。

返回值

查找字符串,或字符 Unicode 编码在字符串出现的位置。

public class Test {
    public static void main(String[] args) {
        String string = "aaa456ac";
        // 查找指定字符是在字符串中的下标。在则返回所在字符串下标;不在则返回-1
        // indexOf(String str); 返回结果:-1,"b"不存在
        System.out.println(string.indexOf("b"));

        // 从第四个字符位置开始往后继续查找,包含当前位置
        // indexOf(String str, int fromIndex); 返回结果:6
        System.out.println(string.indexOf("a",3));

        //(与之前的差别:上面的参数是 String 类型,下面的参数是 int 类型)参考数据:a-97,b-98,c-99

        // 从头开始查找是否存在指定的字符
        // indexOf(int ch);返回结果:7
        System.out.println(string.indexOf(99));
        //indexOf(int ch);返回结果:7
        System.out.println(string.indexOf('c'));

        //从fromIndex查找ch,这个是字符型变量,不是字符串。字符a对应的数字就是97。
        //indexOf(int ch, int fromIndex); 返回结果:6
        System.out.println(string.indexOf(97,3));
        //indexOf(int ch, int fromIndex); 返回结果:6  
        System.out.println(string.indexOf('a',3));
    }
}

// 以上程序执行结果为:
// -1
// 6
// 7
// 7
// 6
// 6
public class Test {
    public static void main(String[] args) {
        String Str = new String("菜鸟教程:www.juejin.cn");
        String SubStr1 = new String("juejin");
        String SubStr2 = new String("cn");

        System.out.print("查找字符 n 第一次出现的位置 :" );
        System.out.println(Str.indexOf( 'n' ));
        System.out.print("从第15个位置查找字符 n 第一次出现的位置 :" );
        System.out.println(Str.indexOf( 'n', 15 ));
        System.out.print("子字符串 SubStr1 第一次出现的位置:" );
        System.out.println( Str.indexOf( SubStr1 ));
        System.out.print("从第15个位置开始搜索子字符串 SubStr1 第一次出现的位置 :" );
        System.out.println( Str.indexOf( SubStr1, 15 ));
        System.out.print("子字符串 SubStr2 第一次出现的位置 :" );
        System.out.println(Str.indexOf( SubStr2 ));
    }
}

// 以上程序执行结果为:
// 查找字符 n 第一次出现的位置 :14
// 从第15个位置查找字符 n 第一次出现的位置 :17
// 子字符串 SubStr1 第一次出现的位置:9
// 从第15个位置开始搜索子字符串 SubStr1 第一次出现的位置 :-1
// 子字符串 SubStr2 第一次出现的位置 :16

intern() 方法实例

public native String intern()

描述

intern() 方法返回字符串对象的规范化表示形式。它遵循以下规则:对于任意两个字符串 s 和 t,当且仅当 s.equals(t) 为 true 时,s.intern() == t.intern() 才为 true。

参数

返回值

一个字符串,内容与此字符串相同,但一定取自具有唯一字符串的池。

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

        System.out.print("规范表示:" );
        System.out.println(Str1.intern());

        System.out.print("规范表示:" );
        System.out.println(Str2.intern());
    }
}

// 以上程序执行结果为:
// 规范表示:www.juejin.com
// 规范表示:WWW.JUEJIN.COM

lastIndexOf() 方法实例

// 该方法有以下几种语法格式:
public int lastIndexOf(int ch)
public int lastIndexOf(int ch, int fromIndex)
public int lastIndexOf(String str)
public int lastIndexOf(String str, int fromIndex)

描述

lastIndexOf()方法有四个重载形式

  • 返回指定 字符 在此字符串中最后一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
  • 返回指定 字符 在此字符串中最后一次出现处的索引,从指定的索引处开始进行反向搜索,如果此字符串中没有这样的字符,则返回 -1。
  • 返回指定 子字符串 在此字符串中最右边出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
  • 返回指定 子字符串 在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索,如果此字符串中没有这样的字符,则返回 -1。

参数

  • ch -- 字符。
  • fromIndex -- 开始搜索的索引位置。
  • str -- 要搜索的子字符串。

返回值

指定子字符串在字符串中最后一次出现处的索引值。

public class Test {
    public static void main(String[] args) {
        String Str = new String("稀土掘金:www.juejin.cn");
        String SubStr1 = new String("juejin");
        String SubStr2 = new String("cn");

        System.out.print("查找字符 w 最后出现的位置 :" );
        System.out.println(Str.lastIndexOf( 'w' ));
        System.out.print("从第15个位置查找字符 n 最后出现的位置 :" );
        System.out.println(Str.lastIndexOf( 'n', 15 ));
        System.out.print("子字符串 SubStr1 最后出现的位置:" );
        System.out.println( Str.lastIndexOf( SubStr1 ));
        System.out.print("从第15个位置开始搜索子字符串 SubStr1最后出现的位置 :" );
        System.out.println( Str.lastIndexOf( SubStr1, 15 ));
        System.out.print("子字符串 SubStr2 最后出现的位置 :" );
        System.out.println(Str.lastIndexOf( SubStr2 ));
    }
}

// 以上程序执行结果为:
// 查找字符 w 最后出现的位置 :7
// 从第15个位置查找字符 n 最后出现的位置 :14
// 子字符串 SubStr1 最后出现的位置:9
// 从第15个位置开始搜索子字符串 SubStr1最后出现的位置 :9
// 子字符串 SubStr2 最后出现的位置 :16

length() 方法实例

public int length()

描述

length() 方法用于返回字符串的长度。空字符串的长度返回 0。

参数

返回值

返回字符串长度。

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

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

// 以上程序执行结果为:
// 字符串 Str1 长度 :14
// 字符串 Str2 长度 :6

matches() 方法实例

public boolean matches(String regex)

描述

matches() 方法用于检测字符串是否匹配给定的正则表达式。

参数

regex -- 匹配字符串的正则表达式。

返回值

在字符串匹配给定的正则表达式时,返回 true。

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

        System.out.print("返回值 :" );
        System.out.println(Str.matches("(.*)juejin(.*)"));

        System.out.print("返回值 :" );
        System.out.println(Str.matches("(.*)google(.*)"));

        System.out.print("返回值 :" );
        System.out.println(Str.matches("www(.*)"));
    }
}

// 以上程序执行结果为:
// 返回值 :true
// 返回值 :false
// 返回值 :true

regionMatches() 方法实例

// 该方法有以下几种语法格式:
public boolean regionMatches(int toffset,
                             String other,
                             int ooffset,
                             int len)

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

描述

regionMatches() 方法用于检测两个字符串在一个区域内是否相等。

参数

  • ignoreCase -- 如果为 true,则比较字符时忽略大小写。
  • toffset -- 此字符串中子区域的起始偏移量。
  • other -- 字符串参数。
  • ooffset -- 字符串参数中子区域的起始偏移量。
  • len -- 要比较的字符数。

返回值

如果字符串的指定子区域匹配字符串参数的指定子区域,则返回 true;否则返回 false。是否完全匹配或考虑大小写取决于 ignoreCase 参数。

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

        System.out.print("返回值 :" );
        System.out.println(Str1.regionMatches(4, Str2, 0, 5));

        System.out.print("返回值 :" );
        System.out.println(Str1.regionMatches(4, Str3, 0, 5));

        System.out.print("返回值 :" );
        System.out.println(Str1.regionMatches(true, 4, Str3, 0, 5));
    }
}

// 以上程序执行结果为:
// 返回值 :true
// 返回值 :false
// 返回值 :true

replace() 方法实例

public String replace(char searchChar, char newChar)

描述

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

参数

  • searchChar -- 原字符。
  • newChar -- 新字符。

返回值

替换后生成的新字符串。

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

        System.out.print("返回值 :" );
        System.out.println(Str.replace('j', 'J'));
    }
}

// 以上程序执行结果为:
// 返回值 :JueJin

replaceAll() 方法实例

public String replaceAll(String regex, String replacement)

描述

replaceAll() 方法使用给定的参数 replacement 替换字符串所有匹配给定的正则表达式的子字符串。

参数

  • regex -- 匹配此字符串的正则表达式。
  • replacement -- 用来替换每个匹配项的字符串。

返回值

成功则返回替换的字符串,失败则返回原始字符串。

public class Test {
    public static void main(String[] args) {
        String Str = new String("www.google.com");
        System.out.print("匹配成功返回值 :" );
        System.out.println(Str.replaceAll("google(.*)", "juejin.cn" ));
        System.out.print("匹配失败返回值 :" );
        System.out.println(Str.replaceAll("(.*)taobao(.*)", "juejin.cn" ));
    }
}

// 以上程序执行结果为:
// 匹配成功返回值 :www.juejin.cn
// 匹配失败返回值 :www.google.com

replaceFirst() 方法实例

public String replaceFirst(String regex,
                           String replacement)

描述

replaceFirst() 方法使用给定的参数 replacement 替换字符串第一个匹配给定的正则表达式的子字符串。

参数

  • regex -- 匹配此字符串的正则表达式。
  • replacement -- 用来替换第一个匹配项的字符串。

返回值

成功则返回替换的字符串,失败则返回原始字符串。

public class Test {
    public static void main(String[] args) {
        String Str = new String("hello juejin,I am from juejin。");

        System.out.print("返回值 :" );
        System.out.println(Str.replaceFirst("juejin", "google" ));
        System.out.print("返回值 :" );
        System.out.println(Str.replaceFirst("(.*)juejin(.*)", "google" ));
    }
}

// 以上程序执行结果为:
// 返回值 :hello google,I am from juejin。
// 返回值 :google

split() 方法实例

// 该方法有以下几种语法格式:
public String[] split(String regex)
public String[] split(String regex, int limit)

描述

split() 方法根据匹配给定的正则表达式来拆分字符串。

参数

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

返回值

字符串数组。

注意

  • . 、 $、 | 和 * 等转义字符,必须得加 \\。
  • 多个分隔符,可以用 | 作为连字符。
public class Test {
    public static void main(String[] args) {
        String str = new String("Welcome-to-JueJin");

        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.juejin.cn");
        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
// JueJin

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

// 转义字符返回值 :
// www
// juejin
// cn

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

startsWith() 方法实例

// 该方法有以下几种语法格式:
public boolean startsWith(String prefix, int toffset)
public boolean startsWith(String prefix)

描述

startsWith() 方法用于检测字符串是否以指定的前缀开始。

参数

  • prefix -- 前缀。
  • toffset -- 字符串中开始查找的位置。

返回值

如果字符串以指定的前缀开始,则返回 true;否则返回 false。

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

        System.out.print("返回值 :" );
        System.out.println(Str.startsWith("www") );

        System.out.print("返回值 :" );
        System.out.println(Str.startsWith("juejin") );

        System.out.print("返回值 :" );
        System.out.println(Str.startsWith("juejin", 4) );
    }
}

// 以上程序执行结果为:
// 返回值 :true
// 返回值 :false
// 返回值 :true

subSequence() 方法实例

public CharSequence subSequence(int beginIndex, int endIndex)

描述

subSequence() 方法返回一个新的字符序列,它是此序列的一个子序列。

参数

  • beginIndex -- 起始索引(包括)。
  • endIndex -- 结束索引(不包括)。

返回值

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

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

        System.out.print("返回值 :" );
        System.out.println(Str.subSequence(4, 10) );
    }
}

// 以上程序执行结果为:
// 返回值 :juejin

substring() 方法实例

// 该方法有以下几种语法格式:
public String substring(int beginIndex)
public String substring(int beginIndex, int endIndex)

描述

substring() 方法返回字符串的子字符串。

参数

  • beginIndex -- 起始索引(包括), 索引从 0 开始。
  • endIndex -- 结束索引(不包括)。

返回值

子字符串。

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

        System.out.print("返回值 :" );
        System.out.println(Str.substring(4) );

        System.out.print("返回值 :" );
        System.out.println(Str.substring(4, 10) );
    }
}

// 以上程序执行结果为:
// 返回值 :456789101112
// 返回值 :456789

toCharArray() 方法实例

public char[] toCharArray()

描述

toCharArray() 方法将字符串转换为字符数组。

参数

返回值

字符数组。

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

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

// 以上程序执行结果为:
// 返回值 :www.juejin.cn

toLowerCase() 方法实例

// 该方法有以下几种语法格式:
public String toLowerCase()
public String toLowerCase(Locale locale)

描述

toLowerCase() 方法将字符串转换为小写。

参数

  • locale -- 特定的区域

返回值

转换为小写的字符串。

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

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

// 以上程序执行结果为:
// 返回值 :www.juejin.cn

toString() 方法实例

public String toString()

描述

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

参数

返回值

字符串本身。

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

        System.out.print("返回值 :" );
        System.out.println( Str.toString() );
    }
}

// 以上程序执行结果为:
// 返回值 :WWW.JUEJIN.COM

toUpperCase() 方法实例

// 该方法有以下几种语法格式:
public String toUpperCase()
public String toUpperCase(Locale locale)

描述

toUpperCase() 方法将字符串小写字符转换为大写。

参数

返回值

字符转换为大写后的字符串。

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

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

// 以上程序执行结果为:
// 返回值 :WWW.JUEJIN.COM

trim() 方法实例

public String trim()

描述

trim() 方法用于删除字符串的头尾空白符。

参数

返回值

删除头尾空白符的字符串。

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

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

// 以上程序执行结果为:
// 原始值 :    www.junjin.com    
// 删除头尾空白 :www.junjin.com
// 该方法有以下几种语法格式:
// 返回 boolean 参数的字符串表示形式
public static String valueOf(boolean b) 
// 返回 char 参数的字符串表示形式
public static String valueOf(char c) 
// 返回 char 数组参数的字符串表示形式
public static String valueOf(char[] data) 
// 返回 char 数组参数的特定子数组的字符串表示形式
public static String valueOf(char[] data, int offset, int count) 
// 返回 double 参数的字符串表示形式
public static String valueOf(double d) 
// 返回 float 参数的字符串表示形式
public static String valueOf(float f) 
// 返回 int 参数的字符串表示形式
public static String valueOf(int i)
// 返回 long 参数的字符串表示形式
public static String valueOf(long l)
// 返回 Object 参数的字符串表示形式
public static String valueOf(Object obj) 

描述

返回参数的字符串表示形式。

参数

  • 指定类型参数。

返回值

返回参数类型的表现形式。

public class Test {
    public static void main(String args[]) {
        double d = 1100.00;
        boolean b = true;
        long l = 1234567890;
        char[] arr = {'j', 'u', 'e', 'j', 'i', 'n' };

        System.out.println("返回值 : " + String.valueOf(d) );
        System.out.println("返回值 : " + String.valueOf(b) );
        System.out.println("返回值 : " + String.valueOf(l) );
        System.out.println("返回值 : " + String.valueOf(arr) );
    }
}

// 以上程序执行结果为:
// 返回值 : 1100.0
// 返回值 : true
// 返回值 : 1234567890
// 返回值 : juejin

contains() 方法实例

public boolean contains(CharSequence chars)

描述

contains() 方法用于判断字符串中是否包含指定的字符或字符串。

参数

  • chars -- 要判断的字符或字符串。

返回值

如果包含指定的字符或字符串返回 true,否则返回 false。

public class Test {
    public static void main(String args[]) {
        String myStr = "JueJin";
        System.out.println(myStr.contains("Jue"));
        System.out.println(myStr.contains("i"));
        System.out.println(myStr.contains("o"));
    }
}

// 以上程序执行结果为:
// true
// true
// false

isEmpty() 方法实例

public boolean isEmpty()

描述

isEmpty() 方法用于判断字符串是否为空。字符串通过length() 方法计算字符串长度,如果返回 0,即为空字符串。

参数

返回值

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

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

// 以上程序执行结果为:
// myStr1 是否为空:false
// myStr2 是否为空:true
// myStr3 长度:4
// myStr3 是否为空:false