百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程字典 > 正文

【Java编程】String类的创建和操作

toyiye 2024-06-21 12:37 8 浏览 0 评论

字符串广泛应用 在 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 对象创建
复制代码

注意: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" 还存在于内存中。

字符串长度

用于获取有关对象的信息的方法称为访问器方法。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(序号)

方法描述

1

char charAt(int index),返回指定索引处的 char 值

2

int compareTo(String anotherString),按字典顺序比较两个字符串

3

int compareToIgnoreCase(String str),按字典顺序比较两个字符串,不考虑大小写

4

String concat(String str),将指定字符串连接到此字符串的结尾

5

boolean contentEquals(StringBuffer sb),当且仅当字符串与指定的StringBuffer有相同顺序的字符时候返回真

6

static String copyValueOf(char[] data),返回指定数组中表示该字符序列的 String

7

static String copyValueOf(char[] data, int offset, int count),返回指定数组中表示该字符序列的 String

8

boolean endsWith(String suffix),测试此字符串是否以指定的后缀结束

9

boolean equals(Object anObject),将此字符串与指定的对象比较

10

boolean equalsIgnoreCase(String anotherString),将此 String 与另一个 String 比较,不考虑大小写

11

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

12

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

13

void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin),将字符从此字符串复制到目标字符数组

14

int hashCode(),返回此字符串的哈希码

15

int indexOf(int ch),返回指定字符在此字符串中第一次出现处的索引

16

int indexOf(int ch, int fromIndex),返回在此字符串中第一次出现指定字符处的索引,从指定的索引开始搜索

17

int indexOf(String str),返回指定子字符串在此字符串中第一次出现处的索引

18

int indexOf(String str, int fromIndex),返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始

19

String intern(),返回字符串对象的规范化表示形式

20

int lastIndexOf(int ch),返回指定字符在此字符串中最后一次出现处的索引

21

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

22

int lastIndexOf(String str),返回指定子字符串在此字符串中最后一次出现处的索引

23

int lastIndexOf(String str, int fromIndex),返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索

24

int length(),返回此字符串的长度

25

boolean matches(String regex),告知此字符串是否匹配给定的正则表达式

26

boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len),测试两个字符串区域是否相等

27

boolean regionMatches(int toffset, String other, int ooffset, int len),测试两个字符串区域是否相等

28

String replace(char oldChar, char newChar),返回一个新的字符串,新的字符串是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的

29

String replaceAll(String regex, String replacement),使用给定的 replacement 替换此字符串所有匹配给定的正则表达式的子字符串

30

String replaceFirst(String regex, String replacement),使用给定的 replacement 替换此字符串匹配给定的正则表达式的第一个子字符串

31

String[] split(String regex),根据给定正则表达式的匹配拆分此字符串

32

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

33

boolean startsWith(String prefix),测试此字符串是否以指定的前缀开始

34

boolean startsWith(String prefix, int toffset),测试此字符串从指定索引开始的子字符串是否以指定前缀开始

35

CharSequence subSequence(int beginIndex, int endIndex),返回一个新的字符序列,它是此序列的一个子序列

36

String substring(int beginIndex),返回一个新的字符串,它是此字符串的一个子字符串

37

String substring(int beginIndex, int endIndex),返回一个新的字符串,它是此字符串的一个子字符串

38

char[] toCharArray(),将此字符串转换为一个新的字符数组

49

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

40

String toLowerCase(Locale locale),使用给定 Locale 的规则将此 String 中的所有字符都转换为小写

41

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

42

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

43

String toUpperCase(Locale locale),使用给定 Locale 的规则将此 String 中的所有字符都转换为大写

44

String trim(),返回字符串的副本,忽略前导空白和尾部空白

45

static String valueOf(primitive data type x),返回给定data type类型x参数的字符串表示形式

46

contains(CharSequence chars),判断是否包含指定的字符系列

47

isEmpty() ,判断字符串是否为空

方法实例:\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

相关推荐

为何越来越多的编程语言使用JSON(为什么编程)

JSON是JavascriptObjectNotation的缩写,意思是Javascript对象表示法,是一种易于人类阅读和对编程友好的文本数据传递方法,是JavaScript语言规范定义的一个子...

何时在数据库中使用 JSON(数据库用json格式存储)

在本文中,您将了解何时应考虑将JSON数据类型添加到表中以及何时应避免使用它们。每天?分享?最新?软件?开发?,Devops,敏捷?,测试?以及?项目?管理?最新?,最热门?的?文章?,每天?花?...

MySQL 从零开始:05 数据类型(mysql数据类型有哪些,并举例)

前面的讲解中已经接触到了表的创建,表的创建是对字段的声明,比如:上述语句声明了字段的名称、类型、所占空间、默认值和是否可以为空等信息。其中的int、varchar、char和decimal都...

JSON对象花样进阶(json格式对象)

一、引言在现代Web开发中,JSON(JavaScriptObjectNotation)已经成为数据交换的标准格式。无论是从前端向后端发送数据,还是从后端接收数据,JSON都是不可或缺的一部分。...

深入理解 JSON 和 Form-data(json和formdata提交区别)

在讨论现代网络开发与API设计的语境下,理解客户端和服务器间如何有效且可靠地交换数据变得尤为关键。这里,特别值得关注的是两种主流数据格式:...

JSON 语法(json 语法 priority)

JSON语法是JavaScript语法的子集。JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔花括号保存对象方括号保存数组JS...

JSON语法详解(json的语法规则)

JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔大括号保存对象中括号保存数组注意:json的key是字符串,且必须是双引号,不能是单引号...

MySQL JSON数据类型操作(mysql的json)

概述mysql自5.7.8版本开始,就支持了json结构的数据存储和查询,这表明了mysql也在不断的学习和增加nosql数据库的有点。但mysql毕竟是关系型数据库,在处理json这种非结构化的数据...

JSON的数据模式(json数据格式示例)

像XML模式一样,JSON数据格式也有Schema,这是一个基于JSON格式的规范。JSON模式也以JSON格式编写。它用于验证JSON数据。JSON模式示例以下代码显示了基本的JSON模式。{"...

前端学习——JSON格式详解(后端json格式)

JSON(JavaScriptObjectNotation)是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。它基于JavaScriptProgrammingLa...

什么是 JSON:详解 JSON 及其优势(什么叫json)

现在程序员还有谁不知道JSON吗?无论对于前端还是后端,JSON都是一种常见的数据格式。那么JSON到底是什么呢?JSON的定义...

PostgreSQL JSON 类型:处理结构化数据

PostgreSQL提供JSON类型,以存储结构化数据。JSON是一种开放的数据格式,可用于存储各种类型的值。什么是JSON类型?JSON类型表示JSON(JavaScriptO...

JavaScript:JSON、三种包装类(javascript 包)

JOSN:我们希望可以将一个对象在不同的语言中进行传递,以达到通信的目的,最佳方式就是将一个对象转换为字符串的形式JSON(JavaScriptObjectNotation)-JS的对象表示法...

Python数据分析 只要1分钟 教你玩转JSON 全程干货

Json简介:Json,全名JavaScriptObjectNotation,JSON(JavaScriptObjectNotation(记号、标记))是一种轻量级的数据交换格式。它基于J...

比较一下JSON与XML两种数据格式?(json和xml哪个好)

JSON(JavaScriptObjectNotation)和XML(eXtensibleMarkupLanguage)是在日常开发中比较常用的两种数据格式,它们主要的作用就是用来进行数据的传...

取消回复欢迎 发表评论:

请填写验证码