Java String字符串类API指南(更新到Java 11)

x33g5p2x  于2021-08-19 转载在 Java  
字(25.1k)|赞(0)|评价(0)|浏览(463)

在本指南中,我们将通过一个例子学习所有字符串类的API/方法。本指南根据Java 11中新增的字符串API进行了更新,并附有一个例子。

Java 11中新的字符串API/方法

以下是Java 11中添加到String类的API/方法。

  • String java.lang.String.repeat(int count) - 顾名思义,repeat()实例方法会重复字符串的内容。
  • String java.lang.String.strip() - strip()实例方法返回一个去除所有前导和尾部白点的字符串。
  • String java.lang.String.stripLeading() - 该方法返回一个去除所有前导白字的字符串。
  • String java.lang.String.stripTrailing() - 该方法返回一个删除了所有尾部空白的字符串。
  • boolean java.lang.String.isBlank() - 如果字符串是空的或者只包含空白,isBlank()实例方法返回true。否则,它返回false。
  • Stream java.lang.String.lines() - lines()实例方法返回一个从字符串中提取的行的Stream,用行的终止符分开。
    请看我的单独教程,了解上述所有新的字符串API的用法,并举例说明:https://www.javaguides.net/2020/02/new-string-apis-methods-in-java-11-examples.html

1. 字符串基础知识

正如我们所知,字符串在Java编程中被广泛使用,是一串字符。在Java编程语言中,字符串是对象。

Java平台提供了java.lang.String类来创建和操作字符串。

###1.1 创建一个字符串对象

有两种方法可以创建一个字符串对象。

  • 通过字符串字面
  • 通过new关键字

使用字符串字面意义

Java字符串字面意义是通过使用双引号创建的。

例如。

String s="javaguides";

每次你创建一个字符串字面,JVM首先检查字符串常量池。如果字符串已经存在于池中,就会返回一个对池中实例的引用。如果字符串不存在于池中,就会创建一个新的字符串实例并放入池中。
比如说

String s1="javaguides";
String s2="javaguides";
//will not create new instance

想知道更多关于字符串池的工作细节,请点击Guide to Java String Constant Pool

现在的问题是,为什么java要使用字符串字面的概念?
很简单,为了使Java的内存效率更高(因为如果字符串常量池中已经存在,就不会再创建新对象)。

使用一个新的关键字

让我们创建一个简单的例子,通过使用new关键字创建String对象来演示。

public static void main(String[] args) {
    String str = new String("Java Guides");
    // create String object using new Keyword
    int length = str.length();
    System.out.println(" length of the string '" + str + "' is :: " + length);
}

输出:

length of the string 'Java Guides' is:: 11

从上面的例子中,JVM将在正常(非池)堆内存中创建一个新的字符串对象,字面意思 "Java Guides "将被放在字符串常量池中。变量str将指代堆(非池)中的对象。
要创建一个由字符数组初始化的字符串,下面是一个例子。

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

;
String s = new String(chars);

让我们通过实例探索所有的字符串API来深入学习字符串。

1.2 Java中字符串类的层次结构

字符串类实现的接口。 Serializable, CharSequence, Comparable< String> 。 请参考java.lang.String上的更多细节。  JavaDoc.


字符串类实现的接口

2. 字符串构造函数

字符串类支持几个构造函数。

  • String() - 初始化一个新创建的String对象,使其代表一个空字符序列。
  • String(byte[] bytes) - 通过使用平台的默认字符集对指定的字节数组进行解码来构造一个新的String。
  • String(byte[] bytes, Charset charset) - 通过使用指定的字符集对指定的字节数组进行解码来构造一个新的字符串。
  • String(byte[] bytes, int offset, int length) - 使用平台默认的字符集对指定的字节子阵列进行解码,构造一个新的字符串。
  • String(byte[] bytes, int offset, int length, Charset charset) - 使用指定的字符集对指定的字节子阵列进行解码,构造一个新的字符串。
  • String(byte[] bytes, int offset, int length, String charsetName) - 使用指定的字符集对指定的字节子阵列进行解码,构造一个新的字符串。
  • String(byte[] bytes, String charsetName) - 通过使用指定的字符集对指定的字节数组进行解码,构造一个新的字符串。
  • String(char[] value) - 分配一个新的String,使其代表当前包含在字符阵列参数中的字符序列。
  • String(char[] value, int offset, int count) - 分配一个新的字符串,包含字符数组参数的一个子数组中的字符。
  • String(int[] codePoints, int offset, int count) - 分配一个新的字符串,包含Unicode码点数组参数的子数组中的字符。
  • String(String original) - 初始化一个新创建的String对象,使其代表与参数相同的字符序列;换句话说,新创建的字符串是参数字符串的一个副本。
  • String(StringBuffer buffer) - 分配一个新的字符串,该字符串包含当前在字符串缓冲区参数中的字符序列。* String(StringBuilder builder) - 分配一个新的字符串,包含当前包含在字符串构建器参数中的字符序列。
    让我们通过例子来学习几个重要的字符串提供的构造器。
  1. **要创建一个空的字符串,请调用默认构造函数。**例如。
String s = new String();

将创建一个没有任何字符的String实例。

  1. **创建一个由字符数组初始化的String。**下面是一个例子。
char chars[] = {
    'a',
    'b',
    'c'
}

;
String s = new String(chars);

这个构造函数用字符串 "abc "来初始化s。

  1. 我们可以使用以下构造函数指定一个字符数组的子范围作为初始化器:
String(char chars[], int startIndex, int numChars)

这里,startIndex指定了子范围开始的索引,numChars指定了要使用的字符数。下面是一个例子。

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

;
String s = new String(chars, 2, 3);

这就用字符的cde初始化了s。

  1. 我们可以用这个构造函数构造一个包含与另一个字符串对象相同字符序列的字符串对象:
String(String strObj)

这里,strObj是一个字符串对象。考虑一下这个例子。

// Construct one String from another.
class MakeString {
    public static void main(String args[]) {
        char c[] = {
            'J',
            'a',
            'v',
            'a'
        }
        ;
        String s1 = new String(c);
        String s2 = new String(s1);
        System.out.println(s1);
        System.out.println(s2);
    }
}

这个程序的输出结果如下。

Java Java

你可以看到,s1和s2包含相同的字符串。

  1. **字符串类提供了构造函数,当给定一个字节数组时,可以初始化一个字符串。 **这里显示了两种形式。
String(byte chrs[]) String(byte chrs[], int startIndex, int numChars)

这里,chris指定的是字节数组。第二种形式允许你指定一个子范围。在每个构造函数中,字节到字符的转换是通过使用平台的默认字符编码完成的。下面的程序说明了这些构造函数。

// Construct string from subset of char array.
class SubStringCons {
    public static void main(String args[]) {
        byte ascii[] = {
            65,
            66,
            67,
            68,
            69,
            70
        }
        ;
        String s1 = new String(ascii);
        System.out.println(s1);
        String s2 = new String(ascii, 2, 3);
        System.out.println(s2);
    }
}

这个程序产生了以下输出:

ABCDEF CDE
  1. 我们可以使用字符串构造函数从StringBuffer和StringBuilder中构造一个字符串
String(StringBuffer strBufObj) String(StringBuilder strBuildObj)

例子。

String string = new String(new StringBuffer("JavaGuides"));
System.out.println(string);
String string2 = new String(new StringBuilder("JavaGuides"));
System.out.println(string2);

输出:

JavaGuides JavaGuides

3. 所有字符串API/方法及实例

charAt(int index)

要从一个字符串中提取单个字符,你可以通过charAt()方法直接引用单个字符。

例1:  返回这个字符串中指定索引处的char值。第一个char值在索引0处。

String str = "Welcome to string handling guide";
char ch1 = str.charAt(0);
char ch2 = str.charAt(5);
char ch3 = str.charAt(11);
char ch4 = str.charAt(20);
System.out.println("Character at 0 index is: " + ch1);
System.out.println("Character at 5th index is: " + ch2);
System.out.println("Character at 11th index is: " + ch3);
System.out.println("Character at 20th index is: " + ch4);

输出:

Character at 0 index is: W Character at 5th index is: m Character at 11th index is: s Character at 20th index is: n

例2:抛出IndexOutOfBoundsException - 如果索引参数是负数或者不小于这个字符串的长度。

String str = "Java Guides";
char ch1 = str.charAt(str.length() + 1);
System.out.println("character :: " + ch1);

输出:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 12 at java.lang.String.charAt(String.java:658) at com.javaguides.strings.methods.ChatAtExample.charAtExample2(ChatAtExample.java:26) at com.javaguides.strings.methods.ChatAtExample.main(ChatAtExample.java:6)

例3:如何获得字符串的第一个和最后一个字符

String str = "Java Guides";
int strLength = str.length();
// Fetching first character
System.out.println("Character at 0 index is: " + str.charAt(0));
// The last Character is present at the string length-1 index
System.out.println("Character at last index is: " + str.charAt(strLength - 1));

输出:

Character at 0 index is: J Character at last index is: s

codePointAt(int index)

该方法返回指定索引处的字符(Unicode代码点)。索引指的是char值(Unicode代码单位),范围从0到length()-1。

如果索引参数为负数或不小于该字符串的长度,该方法会抛出IndexOutOfBoundsException。
例子:

public class CodePointAtExample {
    public static void main(String[] args) {
        String str = "javaguides";
        int unicode = str.codePointAt(0);
        System.out.println("the character (Unicode code point) at the specified index is :: " + unicode);
    }
}

输出:

the character (Unicode code point) at the specified index is:: 106

codePointBefore(int index)

该方法返回指定索引之前的字符(Unicode代码点)。索引指的是char值(Unicode代码单位),范围从1到长度。

如果index参数为负数或不小于该字符串的长度,该方法会抛出IndexOutOfBoundsException。
例子:

public class CodePointBeforeExample {
    public static void main(String[] args) {
        String str = "javaguides";
        int unicode = str.codePointBefore(1);
        System.out.println("the character (Unicode code point)" + "  at the before specified index is :: " + unicode);
    }
}

输出:

the character (Unicode code point) at the before specified index is:: 106

该方法返回该字符串的指定文本范围内的Unicode代码点的数量。文本范围从指定的beginIndex开始,延伸到索引endIndex-1的字符。
如果beginIndex为负数,或者endIndex大于此字符串的长度,或者beginIndex大于endIndex,此方法会抛出IndexOutOfBoundsException。

例子。

public class CodePointCountExample {
    public static void main(String[] args) {
        String str = "javaguides";
        System.out.println("length of the string :: " + str.length());
        int unicode = str.codePointCount(0, str.length());
        System.out.println("the character (Unicode code point) " + " at the specified index is :: " + unicode);
    }
}

输出:

length of the string:: 10 the character (Unicode code point) at the specified index is:: 10

compareTo(String anotherString)

通常,仅仅知道两个字符串是否相同是不够的。对于排序应用,你需要知道哪一个小于、等于、或大于下一个。如果一个字符串在字典中的顺序在另一个之前,那么它就小于另一个。
如果一个字符串在字典中排在另一个字符串的后面,那么它就大于另一个字符串。compareTo()方法就是为了这个目的。它由Comparable interface指定,由String实现。它有这样的一般形式。

int compareTo(String str)

这里,str是被比较的字符串和调用的字符串。比较的结果以数值形式返回,意思是。

  • 小于0 调用的字符串小于str。
  • 大于零 调用的字符串大于str。
  • 零 两个字符串是相等的。
    **示例1:**这里是一个对字符串数组进行排序的示例程序。该程序使用compareTo()来确定泡沫排序的排序顺序。
// A bubble sort for Strings.
public class CompareToSecondExample {
    static String arr[] = {
        "Now",
        "is",
        "the",
        "time",
        "for",
        "all",
        "good",
        "men",
        "to",
        "come",
        "to",
        "the",
        "aid",
        "of",
        "their",
        "country"
    }
    ;
    public static void main(String args[]) {
        for (int j = 0; j < arr.length; j++) {
            for (int i = j + 1; i < arr.length; i++) {
                if (arr[i].compareTo(arr[j]) < 0) {
                    String t = arr[j];
                    arr[j] = arr[i];
                    arr[i] = t;
                }
            }
            System.out.println(arr[j]);
        }
    }
}

这个程序的输出是单词列表:

Now aid all come country for good is men of the the their time to to

从这个例子的输出可以看出,compareTo()考虑到了大写和小写字母。现在 "这个词在所有其他词之前出来,因为它以大写字母开头,这意味着它在ASCII字符集中的数值较低。
例子2: compareTo方法返回不同的值例子

String s1 = "Hello World";
String s2 = "Hello World";
String s3 = "Java";
String s4 = "Guides";
System.out.println(s1.compareTo(s2));
// 0 because both are equal
System.out.println(s1.compareTo(s3));
// -2 because "H" is 2 times lower than "J"
System.out.println(s1.compareTo(s4));
// 1 because "G" is 1 times greater than "H"

输出:

0 -2 1

**例子3:**使用compareTo()方法将字符串与黑色或空字符串进行比较。请注意,与空字符串比较会返回字符串的长度。

String s1 = "hello";
String s2 = "";
String s3 = "me";
// compare with empty string, returns length of the string
System.out.println(s1.compareTo(s2));
// If first string is empty, result would be negative
System.out.println(s2.compareTo(s3));

输出:

5 -2

compareToIgnoreCase(String str)

对两个字符串进行按字母顺序的比较,忽略大小写差异。该方法返回一个整数,其符号为调用compareTo时的符号,其中每个字符的大小写差异已经通过调用Character.toLowerCase(Character.toUpperCase(character))消除。

例子。

String s1="Hello World";
String s2="hello world";
String s3="Java";
String s4="java";
System.out.println(s1.compareToIgnoreCase(s2));
System.out.println(s3.compareToIgnoreCase(s4));

输出:

0 0

如果指定的字符串大于、等于或小于该字符串,该方法返回一个负整数、零或正整数,忽略大小写的考虑。

concat(String str)

将指定的字符串连接到这个字符串的末尾。

该方法创建一个新的对象,该对象包含调用的字符串,并将str的内容附加到结尾。 concat()执行的功能与+相同。
例子:

public class ConcatExmaple {
    public static void main(String[] args) {
        String str = "javaguides";
        str = str.concat(".net");
        System.out.println("Concatenates the specified string to the end of this string : " + str);
        System.out.println("cares".concat("s"));
        System.out.println("to".concat("get"));
    }
}

输出:

Concatenates the specified string to the end of this string: javaguides.net caress toget

contains(CharSequence s)

当且仅当这个字符串包含指定的char值序列时返回true。

示例:

public class ContainsExample {
    public static void main(String[] args) {
        String str = "javaguides";
        boolean contains = str.contains("guides");
        System.out.println("Contains : " + contains);
    }
}

输出:

Contains: true

contentEquals()

有两个版本的contentEquals方法。

contentEquals(CharSequence cs) - 将此字符串与指定的CharSequence进行比较。
contentEquals(StringBuffer sb) - 将此字符串与指定的StringBuffer进行比较。
例子:

public class ContentEqualsExample {
    public static void main(String[] args) {
        String str = "javaguides";
        String subStr = "javaguides";
        boolean isContentEquals = str.contentEquals(subStr);
        System.out.println("isContentEquals :: " + isContentEquals);
        isContentEquals = str.contentEquals(new StringBuffer(subStr));
        System.out.println("isContentEquals :: " + isContentEquals);
    }
}

输出:

isContentEquals:: true isContentEquals:: true

endsWith(String suffix)

该方法测试该字符串是否以指定的后缀结束。如果参数所代表的字符序列是这个对象所代表的字符序列的后缀,则返回真;否则返回假。

例子。

public class EndsWithExample {
    public static void main(String[] args) {
        String str = "javaguides";
        String subStr = "guides";
        boolean endsWith = str.endsWith(subStr);
        System.out.println(str + " endsWith " + subStr +"  :: " + endsWith);
    }
}

输出:

javaguides endsWith guides:: true

equals(Object anObject) and equalsIgnoreCase(String anotherString)

要比较两个字符串是否相等,使用equals()。它有这样的一般形式。

boolean equals(Object str)

这里,str是字符串对象与调用的字符串对象进行比较。如果两个字符串以相同的顺序包含相同的字符,则返回真,否则返回假。这种比较是区分大小写的。

要执行忽略大小写差异的比较,请调用 equalsIgnoreCase()。当它比较两个字符串时,它认为A-Z与a-z是一样的。它有这样的一般形式。

boolean equalsIgnoreCase(String str)

这里,str是字符串对象与调用的字符串对象进行比较。如果这两个字符串以相同的顺序包含相同的字符,它也会返回真,否则返回假。
下面是一个演示equals()和equalsIgnoreCase()的例子。

// Demonstrate equals() and equalsIgnoreCase().
class equalsDemo {
    public static void main(String args[]) {
        String s1 = "Hello";
        String s2 = "Hello";
        String s3 = "Good-bye";
        String s4 = "HELLO";
        System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2));
        System.out.println(s1 + " equals " + s3 + " -> " + s1.equals(s3));
        System.out.println(s1 + " equals " + s4 + " -> " + s1.equals(s4));
        System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " + s1.equalsIgnoreCase(s4));
    }
}

程序的输出显示在这里:

Hello equals Hello ->
true Hello equals Good-bye ->
false Hello equals HELLO ->
false Hello equalsIgnoreCase HELLO ->
true

例2:

public class EqualsExample {
    public static void main(String[] args) {
        String str = "javaguides";
        String str1 = "javaguides";
        String str3 = "javatutorial";
        boolean equal = str.equals(str1);
        System.out.println(" Is both string are equal :: " + equal);
    }
}

输出:

Is both string are equal:: true

例3:

public class EqualsIgnoreCaseExample {
    public static void main(String[] args) {
        String str = "javaguides";
        boolean equal = str.equalsIgnoreCase("JAVAguides");
        System.out.println("Strings are equal :: " + equal);
    }
}

输出:

Strings are equal:: true

getBytes()

getBytes()方法有四个版本。有一个替代getChars()的方法,将字符存储在一个字节数组中。 byte[] getBytes() - 使用平台的默认字符集将此字符串编码为一串字节,将结果存储到一个新的字节数组中。

byte[] getBytes(Charset charset) - 使用给定的字符集将该字符串编码成一串字节,并将结果存储到一个新的字节数组中。
void getBytes(int srcBegin, int srcEnd, byte[] dst, int dstBegin) - 已废弃。

byte[] getBytes(String charsetName) - 使用指定的字符集将该字符串编码为一串字节,将结果存储到一个新的字节数组中。
让我们写一个例子来演示所有的getBytes()方法。

public class GetBytesExamples {
    public static void main(String[] args) throws UnsupportedEncodingException {
        String str = "javaguides";
        // Encodes this String into a sequence of bytes using the platform's
        // default charset, storing the result into a new byte array.
        byte[] bs = str.getBytes();
        for (byte b :  bs) {
            System.out.println(b);
        }
        // Encodes this String into a sequence of bytes using the given charset,
        // storing the result into a new byte array.
        byte[] bs1 = str.getBytes(Charset.forName("UTF-8"));
        for (byte b : bs1) {
            System.out.println(b);
        }
        // Encodes this String into a sequence of bytes using the given charset,
        // storing the result into a new byte array.
        byte[] bs2 = str.getBytes("UTF-8");
        for (byte b : bs2) {
            System.out.println(b);
        }
        byte[] dest = new byte[str.length()];
        str.getBytes(0, str.length(), dest, 0);
        for (byte b : dest) {
            System.out.println(b);
        }
    }
}

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

如果你需要一次提取一个以上的字符,你可以使用getChars()方法。它有这样的一般形式。

void getChars(int sourceStart, int sourceEnd, char target[], int targetStart)

在这里,sourceStart指定了子串开始的索引,sourceEnd指定了所需子串结束后的一个索引。因此,子串包含从sourceStart到sourceEnd-1的字符。
接收这些字符的数组是由target指定的。子串在目标中被复制的索引在targetStart中被传递。必须注意确保目标数组足够大,以容纳指定子串中的字符数。

下面的程序演示了getChars()。

class getCharsDemo {
    public static void main(String args[]) {
        String s = "This is a demo of the getChars method.";
        int start = 10;
        int end = 14;
        char buf[] = new char[end - start];
        s.getChars(start, end, buf, 0);
        System.out.println(buf);
    }
}

下面是这个程序的输出:

demo

hashCode()

返回这个字符串的哈希代码。字符串对象的哈希代码的计算方法是

s[0]/*31^(n-1) + s[1]/*31^(n-2) + ... + s[n-1]

使用int运算,其中s[i]是字符串的第i个字符,n是字符串的长度,^表示指数化。(空字符串的哈希值为零)。

例子。

public class HashcodeExample {
    public static void main(String[] args) {
        String str = "javaguides";
        int hashcode = str.hashCode();
        System.out.println("hashcode of " + str + " is :: " + hashcode);
    }
}

输出:

hashcode of javaguides is:: -138203751

indexOf()

在java中有4种类型的indexOf方法。下面给出了indexOf方法的签名。

  • indexOf(int ch) - 返回这个字符串中第一次出现的指定字符的索引。
  • indexOf(int ch, int fromIndex) - 返回这个字符串中第一次出现的指定字符的索引,从指定的索引开始搜索。
  • indexOf(String str) - 返回指定子串的第一次出现在这个字符串中的索引。
  • indexOf(String str, int fromIndex) - 返回指定子串第一次出现在这个字符串中的索引,从指定的索引开始。
    例子。这个程序演示了所有4种indexOf()方法的例子。
public class IndexOfExample {
    public static void main(String[] args) {
        String str = "javaguides";
        // method 1
        int index = str.indexOf("java");
        System.out.println(index);
        // Remember index starts with 0 so count from 0
        System.out.println("index of guides :: " + str.indexOf("guides"));
        System.out.println(" index of des :: " + str.indexOf("des"));
        // method 2
        System.out.println(str.indexOf('s'));
        // method 3
        System.out.println(str.indexOf('g', 0));
        // method 4
        System.out.println(str.indexOf("guides", 3));
    }
}

输出:

0 index of guides:: 4 index of des:: 7 9 4 4

intern()

返回字符串对象的标准表示法。

一个字符串池,最初是空的,由String类私下维护。
例子。

public class InternExample {
    public static void main(String[] args) {
        String str = "javaguides";
        String newStr = new String("javaguides");
        System.out.println(newStr.intern().equals(str));
        System.out.println(newStr.equals(str));
        newStr.intern();
        str.intern();
    }
}

输出:

true true

lastIndexOf()方法

java中的lastIndexOf方法有4种类型。LastIndexOf方法的签名如下。

  • lastIndexOf(int ch) - 返回这个字符串中最后出现的指定字符的索引。
  • lastIndexOf(int ch, int fromIndex) - 返回这个字符串中最后出现的指定字符的索引,从指定索引开始向后搜索。
  • lastIndexOf(String str) - 返回指定子串最后出现在这个字符串中的索引。
  • lastIndexOf(String str, int fromIndex) - 返回这个字符串中最后出现的指定子串的索引,从指定索引开始向后搜索。
    lastIndexOf()的主要用途 - 搜索一个字符或子串的最后出现的位置。

例子。这个程序演示了所有4个lastIndexOf()方法的用法。

public class LastIndexOfExample {
    public static void main(String[] args) {
        String str = "javaguides";
        // method1
        int lastIndexOf = str.lastIndexOf('s');
        System.out.println(" last index of given character 's' in' " + " "+ str+"' ::  " + lastIndexOf);
        // method 2
        lastIndexOf = str.lastIndexOf("guides");
        System.out.println(" last index of given string 'guides' in' " + " "+ str+"' ::  " + lastIndexOf);
        // method 3
        lastIndexOf = str.lastIndexOf("guides", 4);
        System.out.println(" last index of guides in given  string " + " "+ str+" and from index  " + lastIndexOf);
        // method 4
        lastIndexOf = str.lastIndexOf('g', str.length());
        System.out.println(" last index of given char ::  " + lastIndexOf);
    }
}

输出:

last index of given character 's' in'  javaguides':: 9 last index of given string 'guides' in'  javaguides':: 4 last index of guides in given string javaguides and from index 4 last index of given char:: 4

length()

一个字符串的长度是它所包含的字符数。要获得这个值,可以调用length()方法,如下图所示。

int length()

例子。打印字符串 "Java Guides "的长度的例子。

public class LengthExample {
    public static void main(String[] args) {
        String str = new String("Java Guides");
        int length = str.length();
        System.out.println(" length of the string '" + str + "' is :: " + length);
    }
}

输出:

length of the string 'Java Guides' is:: 11

regionMatches()方法

regionMatches()方法有两种类型。

  • regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) - 测试两个字符串区域是否相等。
  • regionMatches(int toffset, String other, int ooffset, int len) - 测试两个字符串区域是否相等。
    例子。测试两个字符串区域是否相等的例子。
public class RegionMatchesExample {
    public static void main(String[] args) {
        String str = "javaguides";
        String subStr = "guides";
        boolean b = str.regionMatches(0, subStr, str.length(), str.length());
        boolean b1 = str.regionMatches(true, 0, str, 0, str.length());
        System.out.println(b);
        System.out.println(b1);
    }
}

输出:

false true

replace()方法

replace()方法有两种形式。第一种是用另一个字符替换调用字符串中所有出现的一个字符。它的一般形式如下。

String replace(char original, char replacement)

这里,original指定了要被替换掉的字符。结果字符串被返回。例如。

String s = "Hello".replace('l', 'w');

将字符串 "Hewwo "放入s。

replace()的第二种形式是将一个字符序列替换成另一个字符序列。它有这样的一般形式。

String replace(CharSequence original, CharSequence replacement)

例子。这是一个完整的例子,演示replace()方法的用法。

public class ReplaceExample {
    public static void main(String[] args) {
        String str = "javaguides";
        String subStr = str.replace('a', 'b');
        System.out.println("replace char 'a' with char 'b' from given string : " + subStr);
        subStr = str.replace("guides", "tutorials");
        System.out.println("replace guides with tutorials from given string : " + subStr);
        subStr = str.replaceAll("[a-z]", "java");
        System.out.println(subStr);
        subStr = str.replaceFirst("[a-z]", "java");
        System.out.println(subStr);
    }
}

输出:

replace char 'a' with char 'b' from given string: jbvbguides replace guides with tutorials from given string: javatutorials javajavajavajavajavajavajavajavajavajava javaavaguides

replaceAll(String regex, String replacement)

将此字符串中与给定的正则表达式相匹配的每个子串替换为给定的替换。

例子。这是一个完整的例子来演示 replaceAll() 方法的用法。

public class ReplaceExample {
    public static void main(String[] args) {
        String str = "javaguides";
        String subStr = str.replaceAll("[a-z]", "java");
        System.out.println(subStr);
    }
}

输出:

javajavajavajavajavajavajavajavajavajava

replaceFirst(String regex, String replacement)

将此字符串中与给定的正则表达式相匹配的第一个子串替换为给定的替换。

例子。这是一个完整的例子来演示 replaceFirst() 方法的用法。

public class ReplaceExample {
    public static void main(String[] args) {
        String str = "javaguides";
        String subStr = str.replaceFirst("[a-z]", "java");
        System.out.println(subStr);
    }
}

输出:

javaavaguides

split()方法

有两种形式的split()方法。

  • split(String regex) 围绕给定的正则表达式的匹配来分割这个字符串。 
  • split(String regex, int limit) - 围绕给定的正则表达式的匹配来分割这个字符串。

例子。这是一个完整的例子来演示split()方法的用法。

public class SplitExample {
    public static void main(String[] args) {
        String str = "java,guides.net";
        String[] strArray = str.split(",");
        for (int i = 0;
        i <
         strArray.length;
        i++) {
            System.out.println(strArray[i]);
        }
        strArray = str.split(",", 0);
        for (int i = 0;
        i <
         strArray.length;
        i++) {
            System.out.println(strArray[i]);
        }
    }
}

输出:

java guides.net java guides.net 

startsWith()方法

startsWith()方法有两种形式。

  • startsWith(String prefix) - 测试这个字符串是否以指定的前缀开始。
  • boolean startsWith(String prefix, int toffset) - 测试这个字符串中从指定索引开始的子串是否以指定的前缀开始。
    startsWith()方法决定了一个给定的字符串是否以指定的字符串开始。

例子。这是一个完整的例子来演示startsWith()方法的用法。

public class StartsWithExample {
    public static void main(String[] args) {
        String str = "javaguides";
        boolean startWith = str.startsWith("ja");
        System.out.println("startWith :: " +startWith);
        // Remember index starts from 0
        boolean startWithOffset = str.startsWith("guides", 4);
        System.out.println("startWithOffset :: " + startWithOffset);
    }
}

输出:

startWith:: true startWithOffset:: true

subSequence(int beginIndex, int endIndex)

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

调用此方法的形式为

str.subSequence(begin, end)

的调用,其行为与调用

str.substring(begin, end)

例子。这是一个完整的例子,演示subSequence()方法的用法。

public class SubSequenceExample {
    public static void main(String[] args) {
        String str = "javaguides";
        CharSequence subStr = str.subSequence(0, str.length());
        System.out.println("Returns a character sequence that " + " is a subsequence of this sequence : " + subStr);
    }
}

输出:

Returns a character sequence that is a subsequence of this sequence: javaguides

substring()方法

substring()方法有两种形式。

  • String substring(int beginIndex) - 返回一个属于此字符串的子字符串。 
  • String substring(int beginIndex, int endIndex) - 返回一个属于此字符串的子串的字符串。
    如果beginIndex是负数或者大于这个String对象的长度,这些方法会引发IndexOutOfBoundsException。

例子。这是一个完整的例子来演示substring()方法的用法。

public class SubStringExample {
    public static void main(String[] args) {
        String str = "javaguides";
        // substring from start to end
        String subStr = str.substring(0, str.length());
        System.out.println("substring from 0 to length of the string : " + subStr);
        subStr = str.substring(4);
        System.out.println("Sub string starts from index 4 : " + subStr);
        // Remember index starts from 0
        System.out.println(str.substring(1));
        System.out.println("unhappy".substring(2));
        System.out.println("Harbison".substring(3));
        System.out.println("emptiness".substring(8));
    }
}

输出:

substring from 0 to length of the string: javaguides Sub string starts from index 4: guides avaguides happy bison s

char[] java.lang.String.toCharArray()

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

例子。这是一个完整的例子,演示toCharArray()方法的用法。

public class ToCharArrayExample {
    public static void main(String[] args) {
        String str = "javaguides";
        char[] characters = str.toCharArray();
        for (char c :  characters) {
            System.out.println(c);
        }
    }
}

输出:

j a v a g u i d e s

toLowerCase()方法

有两种形式的toLowerCase()方法。

  • toLowerCase() - 使用默认地区的规则将这个字符串中的所有字符转换为小写。
  • String toLowerCase(Locale locale) - 使用给定的Locale规则将这个字符串中的所有字符转换为小写。
    例子。这是一个完整的例子,演示了toLowerCase()方法的用法。
public class ToLowerCaseExample {
    public static void main(String[] args) {
        String str = "JAVAGUIDES";
        String subStr = str.toLowerCase();
        System.out.println(subStr);
        subStr = str.toLowerCase(Locale.ENGLISH);
        System.out.println(subStr);
    }
}

输出:

javaguides javaguides

toString()

这个对象(已经是一个字符串了!)本身被返回。例子。

public class ToStringExample {
    public static void main(String[] args) {
        String str = "javaguides";
        System.out.println(str.toString());
    }
}

输出:

javaguides

toUpperCase()方法

有两种形式的toUpperCase()方法。

  • toUpperCase() - 使用默认地区的规则将该字符串中的所有字符转换为大写。
  • String toUpperCase(Locale locale) - 使用给定的Locale规则将这个字符串中的所有字符转换为大写字母。
    例子。这是一个完整的例子,演示了toUpperCase()方法的用法。
public class ToUpperCaseExample {
    public static void main(String[] args) {
        String str = "javaguides";
        String subStr = str.toUpperCase();
        System.out.println(subStr);
        subStr = str.toUpperCase(Locale.ENGLISH);
        System.out.println(subStr);
    }
}

输出:

JAVAGUIDES JAVAGUIDES

trim()

返回一个字符串,其值是这个字符串,并去除任何前导和尾部的空白。

例子。这是一个完整的例子来演示trim()方法的用法。

public class TrimExample {
    public static void main(String[] args) {
        String str = "javaguides ";
        String subStr = str.trim();
        System.out.println("trim the space from given string : " + subStr);
    }
}

输出:

trim the space from given string: javaguides

valueOf()

valueOf()方法将数据从其内部格式转换为人类可读的形式。

Java字符串valueOf()方法将不同类型的值转换为一个字符串。在string valueOf()方法的帮助下,你可以将int转换为字符串,long转换为字符串,布尔转换为字符串,字符转换为字符串,浮点转换为字符串,双倍转换为字符串,对象转换为字符串,char数组转换为字符串。
下面是它的几种形式,字符串valueOf()方法的签名或语法如下。

public static String valueOf(boolean b) public static String valueOf(char c) public static String valueOf(char[] c) public static String valueOf(int i) public static String valueOf(long l) public static String valueOf(float f) public static String valueOf(double d) public static String valueOf(Object o)

例子。让我们看一个例子,我们要把所有的基元和对象转换为字符串。

public class StringValueOfExample5 {
    public static void main(String[] args) {
        boolean b1=true;
        byte b2=11;
        short sh = 12;
        int i = 13;
        long l = 14L;
        float f = 15.5f;
        double d = 16.5d;
        char chr[]= {
            'j',
            'a',
            'v',
            'a'
        }
        ;
        StringValueOfExample5 obj=new StringValueOfExample5();
        String s1 = String.valueOf(b1);
        String s2 = String.valueOf(b2);
        String s3 = String.valueOf(sh);
        String s4 = String.valueOf(i);
        String s5 = String.valueOf(l);
        String s6 = String.valueOf(f);
        String s7 = String.valueOf(d);
        String s8 = String.valueOf(chr);
        String s9 = String.valueOf(obj);
        System.out.println(s1);
        System.out.println(s2);
        System.out.println(s3);
        System.out.println(s4);
        System.out.println(s5);
        System.out.println(s6);
        System.out.println(s7);
        System.out.println(s8);
        System.out.println(s9);
    }
}

输出:

true 11 12 13 14 15.5 16.5 java StringValueOfExample5@2a139a55

查看我的从初学者到专家的顶级Java String Tutorial
**如果有任何建议,请发表评论,以改进这个字符串API指南,因为它对每个人都非常有用。

GitHub 仓库

参考资料

相关文章

微信公众号

最新文章

更多