String類方法詳解

本文涵蓋了String類的多個(gè)重要方法并詳細(xì)講解了它們的作用:

String Methods
  • 獲取字符串的長(zhǎng)度:
    length()方法
  • 獲取到字符串某個(gè)索引處的char:
    charAt()方法
  • 用字符串生成char數(shù)組的方法:
    getChars()
  • 比較字符串對(duì)象是否相等:
    equals()方法
  • 忽略大小寫時(shí)比較字符串對(duì)象是否相等:
    equalsIgnoreCase()方法
  • 判斷兩個(gè)字符串對(duì)象的指定區(qū)間是否匹配:
    regionMatches()方法
  • 判斷字符串對(duì)象是否以指定的字符或字符串開頭或結(jié)尾
    startsWith() & endsWith()方法:
  • 定位字符或子字符串:
    indexOf() & lastIndexOf() 方法
  • 從字符串中截取子字符串:
    substring()方法
  • 拼接字符串:
    concat()方法
  • 替換字符串中的某個(gè)字符或子字符串:
    replace()
  • 將字符串對(duì)象大寫或小寫:
    toUpperCase()、toLowerCase()
  • 去掉字符串對(duì)象前后的空格:
    trim()方法:
  • 接收任何種類的參數(shù),并將其轉(zhuǎn)化為字符串對(duì)象:
    String.valueOf()方法:

最初和String類打交道的時(shí)候,因?yàn)樗R娏?,一直都想?dāng)然地認(rèn)為String類型也是基本類型的一種。
后來才發(fā)現(xiàn),原來String也是一個(gè)類。
既然是類,那就肯定有對(duì)象,因此也必須要有構(gòu)造器

java為String類提供了多個(gè)重載的構(gòu)造器:

public class StringConstructors{
    public static void main(String[] args) {
//生成一個(gè)char數(shù)組,之后會(huì)用到其中的char來生成String對(duì)象
        char [] charArray = 
            new char[] {'h','e','l','l','o','w','o','r','l','d'}; 
        String st = new String("hello");

        //構(gòu)造器
        String s1 = new String();
        String s2 = new String(st);
        String s3 = new String (charArray);
        String s4 = new String (charArray,5,5);

        System.out.printf("s1 = %s%ns2 = %s%ns3 = %s%ns4 = %s%n",
            s1,s2,s3,s4);
    }
}

輸出:

s1 = 
s2 = hello
s3 = helloworld
s4 = world

注:s4用到的構(gòu)造器傳入的兩個(gè)int類型的參數(shù):

  • 第一個(gè)表示index。由于數(shù)組是從0開始計(jì)數(shù)的,所以,index = 5 指的也就是從第6個(gè)插入開始算。
  • 第二個(gè)表示往后數(shù)的個(gè)數(shù),結(jié)合本例子中的index =5,也就是從第六個(gè)char開始,往后數(shù)5個(gè)char。

因此輸出的就是 “world”。

獲取字符串的長(zhǎng)度——length()
獲取到字符串某個(gè)索引處的char——charAt()
用字符串生成char數(shù)組——getChars()
public class StringMiscellaneous{
    public static void main(String[] args) {
        String s1 = "hello world";
        char [] charArray= new char [5];
//輸出s1的值
        System.out.printf("s1的值: %s",s1);
//length()方法
        System.out.printf("%ns1的長(zhǎng)度:%d ",s1.length());
//charAt()方法 輸出s1的每一個(gè)char
        System.out.printf("%n輸出s1的每一個(gè)char:%n");
        for (int count =0; count <s1.length() ; count ++) {
            System.out.printf("%c ",s1.charAt(count));
        }
        
//反轉(zhuǎn)輸出s1的每一個(gè)char
        System.out.printf("%n反轉(zhuǎn)輸出s1的每一個(gè)char:%n");
        for (int count = s1.length()-1 ;count >=0;count-- ) {
            System.out.printf("%c ",s1.charAt(count));
        }
        System.out.println();

        s1.getChars(0,5,charArray,0);
        System.out.printf("輸出由s1得到的char數(shù)組:%n");
        for (char character : charArray ) {
            System.out.print(character);
        }
        System.out.println();
    }
}

輸出:

s1的值: hello world
s1的長(zhǎng)度:11 
輸出s1的每一個(gè)char:
h e l l o   w o r l d 
反轉(zhuǎn)輸出s1的每一個(gè)char:
d l r o w   o l l e h 
輸出由s1得到的char數(shù)組:
hello

注:s1.getChars(0,5,charArray,0);方法中的參數(shù)依次為:

  • 第一個(gè)參數(shù)代表從String對(duì)象復(fù)制char的開始索引,這里傳入1也就是從第一個(gè)char開始復(fù)制;
  • 第二個(gè)參數(shù)代表從String對(duì)象復(fù)制字符時(shí)結(jié)尾的index,這里傳入6,說明復(fù)制的范圍應(yīng)該是[0,6), 也就是說不包括該索引所在位置的char;
  • 第三個(gè)參數(shù)傳入存放char的數(shù)組;
  • 第四個(gè)參數(shù)代表將char復(fù)制到指定數(shù)組的開始索引。這里傳入0也就表示從charArray數(shù)組的index = 0的位置開始寫入復(fù)制的char。

比較字符串對(duì)象是否相等:

public class StringComparation{
    public static void main(String[] args) {
        String s1 = new String("hello"); //s1復(fù)制了hello字符串的值
        String s2 = "good day";
        String s3 = "Have a nice day";
        String s4 = "have a nice day";
        //輸出s1,s2,s3,s4的值:
        System.out.printf("s1 = %s%ns2 = %s%ns3 = %s%ns4 = %s%n%n",
            s1,s2,s3,s4);
        //equals()方法
        if (s1.equals("hello")) 
            System.out.println("s1 equals \"hello\"");
        else
            System.out.println("s1 does not equals \"hello\"");
    }
}

輸出:

s1 = hello
s2 = good day
s3 = Have a nice day
s4 = have a nice day

s1 equals "hello"

從輸出結(jié)果可以看出,equals()方法比較的是內(nèi)容。也就是只要字符串的內(nèi)容相等,equals()方法就返回true。

但是,如果用 “==”來做比較,情況則有所不同:

if (s1 == "hello") 
            System.out.println("s1 和\"hello\"是同一個(gè)對(duì)象");
        else
            System.out.println("s1 和 \"hello\"不是同一個(gè)對(duì)象");
        String s5 = new String("hello");
        if (s1 == s5) 
            System.out.println("s1和s5 是同一個(gè)對(duì)象");
        else
            System.out.println("s1和s5不是同一個(gè)對(duì)象");

輸出:

s1和"hello"不是同一個(gè)對(duì)象
s1和s5不是同一個(gè)對(duì)象

在java中,當(dāng)基礎(chǔ)類型的值通過“==”來作比較時(shí),如果兩個(gè)基礎(chǔ)類型的值相等,則返回true。但如果用“==”來比較引用類型,只有當(dāng)兩個(gè)同時(shí)指向內(nèi)存中的同一個(gè)對(duì)象時(shí)才會(huì)返回true。
s1 = new String ("hello");語句的意思是,新建一個(gè)String對(duì)象,其值復(fù)制自"hello", 并讓變量s1獲得其引用。也就是變量s1指向了這個(gè)新生成的String對(duì)象。
如果換一種寫法,寫成s1 = "hello;",結(jié)果就會(huì)不同了:

String s1 = "hello";
        if (s1 == "hello") 
            System.out.println("s1 和\"hello\"是同一個(gè)對(duì)象");
        else
            System.out.println("s1 和 \"hello\"不是同一個(gè)對(duì)象");
        String s5 = new String("hello");
        if (s1 == s5) 
            System.out.println("s1 和 s5 是同一個(gè)對(duì)象");
        else
            System.out.println("s1 和 s5 不是同一個(gè)對(duì)象");

輸出:

s1 和"hello"是同一個(gè)對(duì)象
s1 和 s5 不是同一個(gè)對(duì)象

這一次,變量s1直接指向了字符串“hello”,而s5與上文中的s1類似。實(shí)際情況是s5指向了新生成的一個(gè)String對(duì)象,而該String對(duì)象的值是從“hello”復(fù)制得到的。
所以,

if (s1.equals(s5)) 
            System.out.println("s1 和 s5 值相等");
        else
            System.out.println("s1 和 s5 值不等");

的輸出結(jié)果為:

s1 和 s5 值相等

忽略大小寫時(shí),判斷字符串是否相等——equalsIgnoreCase()方法:

此方法在比較值是否相等時(shí)會(huì)忽略大小寫:

public class StringComparation{
    public static void main(String[] args) {
        String s1 = new String("hello"); //s1復(fù)制了hello字符串的值
        String s2 = "good day";
        String s3 = "Have a nice day";
        String s4 = "have a nice day";
//輸出s1,s2,s3,s4的值:
        System.out.printf("s1 = %s%ns2 = %s%ns3 = %s%ns4 = %s%n%n",
            s1,s2,s3,s4);
//equalsIgnoreCase()方法:
        if (s3.equalsIgnoreCase(s4)) 
            System.out.printf("忽略大小寫時(shí),%s 等于 %s%n",s3,s4);   
        else 
            System.out.printf("忽略大小寫時(shí),%s 不等于 %s%n",s3,s4);

輸出:

s1 = hello
s2 = good day
s3 = Have a nice day
s4 = have a nice day

忽略大小寫時(shí),Have a nice day 等于 have a nice day

判斷兩個(gè)字符串對(duì)象的指定區(qū)間是否匹配——regionMatches()方法:

此方法用來比較兩個(gè)String對(duì)象的某一區(qū)間是否相等:

        if (s3.regionMatches(0,s4,0,5)) //大小寫敏感
            System.out.println("s3和s4的前五個(gè)字符相等");    
        else
            System.out.println("s3和s4的前五個(gè)字符不相等");
s3和s4的前五個(gè)字符不相等

regionMatches()方法接收4個(gè)參數(shù)時(shí):

  • 第一個(gè)參數(shù),表示s3字符串要做比較的區(qū)間從哪兒開始算起;
  • 第二個(gè)參數(shù)表示要與s3座比較的字符串,這里傳入s4;
  • 第三個(gè)參數(shù)與第一個(gè)類似;
  • 第四個(gè)參數(shù)表示要作比較的區(qū)間的長(zhǎng)度。
    這里由于'h'不等于‘H’,所以該方法返回false。

如果想要忽略掉大小寫來進(jìn)行比較的話,則可以用其重載的另一個(gè)方法,并將第一個(gè)參數(shù)設(shè)置為true:

if (s3.regionMatches(true,0,s4,0,5)) //大小寫不敏感
            System.out.println("s3和s4的前五個(gè)字符相等");    
        else
            System.out.println("s3和s4的前五個(gè)字符不相等");

輸出:

s3和s4的前五個(gè)字符相等

判斷字符串對(duì)象是否以指定的字符或字符串開頭或結(jié)尾——startsWith()&endsWith()方法:

顧名思義,這兩個(gè)方法用來判斷String對(duì)象是否以某字符串或字符開頭或結(jié)尾:

public class StringStartsAndEnds{
    public static void main(String[] args) {
        String [] strings = 
            {"started","starting","to start", "ends","ended","to be ended" };
            //startsWith()方法
            for (String s  : strings) {
                if (s.startsWith("st")) {
                    System.out.printf("\"%s\" starts with \"st\"%n",s);
                }
            }
            //endsWith()方法
            for (String s  : strings) {
                if (s.endsWith("ed")) {
                    System.out.printf("\"%s\" ends with \"ed\"%n",s);
                }
            }
    }
}

輸出:

"started" starts with "st"
"starting" starts with "st"
"started" ends with "ed"
"ended" ends with "ed"
"to be ended" ends with "ed"

定位字符或子字符串——indexOf() & lastIndexOf() 方法

public class MethodsForStringIndex{
    public static void main(String[] args) {
        String letters = "abcdefghigklmnabchilmnopqrstuvwabcde";
        //indexOf()方法
        System.out.printf(
            "'c' 在letters中第一次被找到時(shí)所在的index為:%d%n",
            letters.indexOf('c') );
        System.out.printf(
            "'c' 在letters中,從index=2處往后,第一次被找到時(shí)所在的index為:%d%n",
            letters.indexOf('c',2));//從letters的第三個(gè)字符開始 找
        System.out.printf(
            "'c' 在letters中,從index=3處往后,第一次被找到時(shí)所在的index為:%d%n",
            letters.indexOf('c',3));//從letters的第四個(gè)字符開始 找
    }
}

輸出:

'c' 在letters中第一次被找到時(shí)所在的index為:2
'c' 在letters中,從index=2處往后,第一次被找到時(shí)所在的index為:2
'c' 在letters中,從index=3處往后,第一次被找到時(shí)所在的index為:16

同理,也可以用lastIndexOf()方法來檢索得到某字符最后一次出現(xiàn)時(shí)的index:

System.out.printf(
            "'c' 在letters中最后一次被找到時(shí)所在的index為:%d%n",
            letters.lastIndexOf('c') );
        System.out.printf(
            "'c' 在letters中,從index=33處開始,向前檢索,被再次找到時(shí)所在的index為:%d%n",
            letters.lastIndexOf('c',33) );
        System.out.printf(
            "'c' 在letters中,從index=32處開始,向前檢索,被再次找到時(shí)所在的index為:%d%n",
            letters.lastIndexOf('c',32) );

輸出:

'c' 在letters中最后一次被找到時(shí)所在的index為:33
'c' 在letters中,從index=33處開始,向前檢索,被再次找到時(shí)所在的index為:33
'c' 在letters中,從index=32處開始,向前檢索,被再次找到時(shí)所在的index為:16

以上是對(duì)單個(gè)字符的檢索,對(duì)子字符串的檢索同理:

String subString = "bc";
//indexOf()方法
        System.out.printf("\"bc\"第一次被定位到時(shí)的index為:%d%n",
            letters.indexOf(subString));
        System.out.printf(
            "'bc' 在letters中,從index=1處開始,被再次找到時(shí)所在的index為:%d%n",
            letters.indexOf(subString,1) );
        System.out.printf(
            "'c' 在letters中,從index=2處開始,被再次找到時(shí)所在的index為:%d%n",
            letters.indexOf(subString,2) );

輸出:

"bc"第一次被定位到時(shí)的index為:1
'bc' 在letters中,從index=1處開始,被再次找到時(shí)所在的index為:1
'bc' 在letters中,從index=2處開始,被再次找到時(shí)所在的index為:15

lastIndexOf()方法的情況類似,不再舉例。
最后需要說明的是,如果indexOf()或者lastIndexOf()方法找不到指定的字符或子字符串,則其返回-1:

System.out.println(letters.indexOf('z'));
System.out.println(letters.lastIndexOf("程序猿"));

輸出:

-1
-1

從字符串中截取子字符串:substring()

public class SubStringTest{
    public static void main(String[] args) {
        String letters = "abcdefghigklmnabchilmnopqrstuvwabcde";
        System.out.printf("從index=20處截取到letters的末尾:\"%s\"%n",
            letters.substring(20));
        System.out.printf("從index=5處開始截取,"
            +"一直到index=20處(但不包括index=20):\"%s\"%n",
            letters.substring(5,20));
        System.out.printf("從index=5處開始截取,"
            +"一直到index=21處(此時(shí)包括index=20):\"%s\"%n",
            letters.substring(5,21));

    }
}

輸出:

從index=20處截取到letters的末尾:"mnopqrstuvwabcde"
從index=5處開始截取,一直到index=20處(但不包括index=20):"fghigklmnabchil"
從index=5處開始截取,一直到index=21處(此時(shí)包括index=20):"fghigklmnabchilm"

從輸出結(jié)果可以看出,當(dāng)參數(shù)為sbustring(5,21)時(shí),實(shí)際截取到的值才位于區(qū)間[5,20]。
如果是substring(5,20),則實(shí)際截取到的值位于區(qū)間[5,20)或者說[5,19]。

substring()方法結(jié)合之前的lastIndexOf()方法便可以很輕松地從一個(gè)下載鏈接中獲取到要下載的文件的文件名:

//傳入一個(gè)下載鏈接,這里以簡(jiǎn)書的app下載url為例:
        String url = "http://www.itdecent.cn/apps";
//將url的長(zhǎng)度保存在urlLength變量中:
        int urlLength = url.length();
//"/"符號(hào)最后一次出現(xiàn)時(shí)的index值為:
        int lastSlashIndex = url.lastIndexOf('/');
//用substring()方法截取文件名
        String fileName = url.substring(lastSlashIndex +1,urlLength -1);
        System.out.println("文件名為:"+fileName);

輸出:

文件名為:app

拼接字符串——concat()方法

concat()方法可以用來拼接字符串,拼接前后原字符串的值不會(huì)被修改:

//拼接字符串
        String s1 = "Hello ";
        String s2 = "World";

        System.out.printf("拼接s1和s2得到:%s%n",s1.concat(s2));
        System.out.printf("拼接過后s1的值為:%s%n",s1);
拼接s1和s2得到:Hello World
拼接過后s1的值為:Hello 

replace()、toUpperCase()、toLowerCase()、trim()方法:

public class StringMiscellaneous2{
    public static void main(String[] args) {
        String s1 = "hello";
        String s2 = "GOD BLESS YOU";
        String s3 = "      前后都有好多空格      ";

        System.out.printf("s1 = %s%ns2 = %s%ns3 = %s%n",
            s1,s2,s3);

//replace()方法:
        System.out.printf("用replace()方法把\"hello\"中的'l'換成'L':",
            s1.replace('l','L'));//注意不要漏了引號(hào)

//toLowerCase() & toUpperCase()方法:
        System.out.printf("s2.toLowerCase()=%s%n",s2.toLowerCase());
        System.out.printf("s1.toUpperCase()=%s%n",s1.toUpperCase());

//trim()方法去掉字符串前后多余的空格:
        System.out.printf("s3.trim()=%s%n",s3.trim());
    }
}

輸出:

s1 = hello
s2 = GOD BLESS YOU
s3 =       前后都有好多空格      
用replace()方法把"hello"中的'l'換成'L':s2.toLowerCase()=god bless you
s1.toUpperCase()=HELLO
s3.trim()=前后都有好多空格

接收任何種類的參數(shù),并將其轉(zhuǎn)化為字符串對(duì)象——String.valueOf()方法:

眾所周知,java中所有的對(duì)象都有一個(gè)valueOf()方法,用來輸出該對(duì)象對(duì)自身的文字描述。但是基本類型的數(shù)據(jù)因?yàn)椴荒苁褂梅椒?,所以無法做到這一點(diǎn)。
java中的String類提供了一個(gè)靜態(tài)方法:valueOf()。此方法可以接收任何種類的參數(shù),并將其轉(zhuǎn)化為字符串對(duì)象:

public class StringValueOf{
    public static void main(String[] args) {

        char [] charArray = {'h','e','l','l','o'};
        boolean b = true;
        char ch = 'J';
        int i = 4;
        long l = 100000000L;
        float f= 2.5f;
        double d = 3.333;
        Object oReference = "world"; 

        System.out.printf("char array = %s%n",String.valueOf(charArray));
        System.out.printf("char array 的一部分 = %s%n",
            String.valueOf(charArray,2,3));

        System.out.printf("boolean= %s%n",String.valueOf(b));
        System.out.printf("char= %s%n",String.valueOf(ch));

        System.out.printf("int= %s%n",String.valueOf(i));
        System.out.printf("long= %s%n",String.valueOf(l));

        System.out.printf("float= %s%n",String.valueOf(f));
        System.out.printf("double= %s%n",String.valueOf(d));
        
        System.out.printf("Object= %s%n",String.valueOf(oReference));
    }
}

輸出:

char array = hello
char array 的一部分 = llo
boolean= true
char= J
int= 4
long= 100000000
float= 2.5
double= 3.333
Object= world

水平有限,難免紕漏。
歡迎批評(píng)指正。
諸君共勉:)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • java中String的常用方法 1、length()字符串的長(zhǎng)度 例:char chars[]={'a','b'...
    赤赤有名閱讀 2,194評(píng)論 0 10
  • String類 1、String對(duì)象的初始化 由于String對(duì)象特別常用,所以在對(duì)String對(duì)象進(jìn)行初始化時(shí),...
    簡(jiǎn)詩(shī)閱讀 486評(píng)論 0 1
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法,類相關(guān)的語法,內(nèi)部類的語法,繼承相關(guān)的語法,異常的語法,線程的語...
    子非魚_t_閱讀 34,628評(píng)論 18 399
  • 在編寫程序的過程中,不了避免的要用到字符串,所以String類的常用方法的用法是必須掌握的。學(xué)習(xí)一個(gè)類的使用方法最...
    Geg_Wuz閱讀 1,482評(píng)論 0 4
  • 定義 在一個(gè)方法中定義一個(gè)算法骨架,而將一些步驟延遲到子類中。模板方法使得子類可以在不改變算法結(jié)構(gòu)的情況下,重新定...
    狐尼克朱迪閱讀 202評(píng)論 0 0

友情鏈接更多精彩內(nèi)容