最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java中String類(lèi)常用方法總結(jié)詳解

 更新時(shí)間:2022年08月30日 10:09:40   作者:XIN-XIANG榮  
String類(lèi)是一個(gè)很常用的類(lèi),是Java語(yǔ)言的核心類(lèi),用來(lái)保存代碼中的字符串常量的,并且封裝了很多操作字符串的方法。本文為大家總結(jié)了一些String類(lèi)常用方法的使用,感興趣的可以了解一下

一. String對(duì)象的比較

1. ==比較是否引用同一個(gè)對(duì)象

注意:

對(duì)于內(nèi)置類(lèi)型,==比較的是變量中的值;對(duì)于引用類(lèi)型 , == 比較的是引用中的地址。

public static void main(String[] args) {
        int a = 10;
        int b = 20;
        int c = 10;
        // 對(duì)于基本類(lèi)型變量,==比較兩個(gè)變量中存儲(chǔ)的值是否相同
        System.out.println(a == b); // false
        System.out.println(a == c); // true
        // 對(duì)于引用類(lèi)型變量,==比較兩個(gè)引用變量引用的是否為同一個(gè)對(duì)象
        String s1 = new String("hello");
        String s2 = new String("hello");
        String s3 = new String("world");
        String s4 = s1;
        System.out.println(s1 == s2); // false
        System.out.println(s2 == s3); // false
        System.out.println(s1 == s4); // true
}

2. boolean equals(Object anObject)

按照字典序進(jìn)行比較(字典序:字符大小的順序)

String類(lèi)重寫(xiě)了父類(lèi)Object中equals方法,Object中equals默認(rèn)按照==比較,String重寫(xiě)equals方法后,按照 如下規(guī)則進(jìn)行比較,比如: s1.equals(s2)

String中的equals方法分析:

public boolean equals(Object anObject) {
    // 1. 先檢測(cè)this 和 anObject 是否為同一個(gè)對(duì)象比較,如果是返回true
    if (this == anObject) {
            return true;
    }
    // 2. 檢測(cè)anObject是否為String類(lèi)型的對(duì)象,如果是繼續(xù)比較,否則返回false
    if (anObject instanceof String) {
            // 將anObject向下轉(zhuǎn)型為String類(lèi)型對(duì)象
            String anotherString = (String)anObject;
            int n = value.length;
            // 3. this和anObject兩個(gè)字符串的長(zhǎng)度是否相同,是繼續(xù)比較,否則返回false
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                // 4. 按照字典序,從前往后逐個(gè)字符進(jìn)行比較
                while (n-- != 0) {
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
}

比較示例代碼:

public static void main(String[] args) {
        String s1 = new String("hello");
        String s2 = new String("hello");
        String s3 = new String("Hello");
// s1、s2、s3引用的是三個(gè)不同對(duì)象,因此==比較結(jié)果全部為false
        System.out.println(s1 == s2); // false
        System.out.println(s1 == s3); // false
// equals比較:String對(duì)象中的逐個(gè)字符
// 雖然s1與s2引用的不是同一個(gè)對(duì)象,但是兩個(gè)對(duì)象中放置的內(nèi)容相同,因此輸出true
// s1與s3引用的不是同一個(gè)對(duì)象,而且兩個(gè)對(duì)象中內(nèi)容也不同,因此輸出false
        System.out.println(s1.equals(s2)); // true
        System.out.println(s1.equals(s3)); // false
}

3. int compareTo(String s)

按照字典序進(jìn)行比較

與equals不同的是,equals返回的是boolean類(lèi)型,而compareTo返回的是int類(lèi)型。具體比較方式:

先按照字典次序大小比較,如果出現(xiàn)不等的字符,直接返回這兩個(gè)字符的大小差值

如果前k個(gè)字符相等(k為兩個(gè)字符長(zhǎng)度最小值),返回值兩個(gè)字符串長(zhǎng)度差值

public static void main(String[] args) {
        String s1 = new String("abc");
        String s2 = new String("ac");
        String s3 = new String("abc");
        String s4 = new String("abcdef");
        System.out.println(s1.compareTo(s2)); // 不同輸出字符差值-1
        System.out.println(s1.compareTo(s3)); // 相同輸出 0
        System.out.println(s1.compareTo(s4)); // 前k個(gè)字符完全相同,輸出長(zhǎng)度差值 -3
}

4. int compareToIgnoreCase(String str)

與compareTo方式相同,但是忽略大小寫(xiě)進(jìn)行比較

public static void main(String[] args) {
        String s1 = new String("abc");
        String s2 = new String("ac");
        String s3 = new String("ABc");
        String s4 = new String("abcdef");
        System.out.println(s1.compareToIgnoreCase(s2)); // 不同輸出字符差值-1
        System.out.println(s1.compareToIgnoreCase(s3)); // 相同輸出 0
        System.out.println(s1.compareToIgnoreCase(s4)); // 前k個(gè)字符完全相同,輸出長(zhǎng)度差值 -3
}

二. 字符串查找

字符串查找也是字符串中非常常見(jiàn)的操作,String類(lèi)提供的常用查找的方法,

方法功能
char charAt(int index)返回index位置上字符,如果index為負(fù)數(shù)或者越界,拋出 IndexOutOfBoundsException異常
int indexOf(int ch)返回ch第一次出現(xiàn)的位置,沒(méi)有返回-1
int indexOf(int ch, int fromIndex)從fromIndex位置開(kāi)始找ch第一次出現(xiàn)的位置,沒(méi)有返回-1
int indexOf(String str)返回str第一次出現(xiàn)的位置,沒(méi)有返回-1
int indexOf(String str, int fromIndex) 從fromIndex位置開(kāi)始找str第一次出現(xiàn)的位置,沒(méi)有返回-1
int lastIndexOf(int ch)從后往前找,返回ch第一次出現(xiàn)的位置,沒(méi)有返回-1
int lastIndexOf(int ch, int fromIndex)從fromIndex位置開(kāi)始找,從后往前找ch第一次出現(xiàn)的位置,沒(méi)有返 回-1
int lastIndexOf(String str)從后往前找,返回str第一次出現(xiàn)的位置,沒(méi)有返回-1
int lastIndexOf(String str, int fromIndex)從fromIndex位置開(kāi)始找,從后往前找str第一次出現(xiàn)的位置,沒(méi)有返 回-1
public static void main(String[] args) {
        String s = "aaabbbcccaaabbbccc";
        System.out.println(s.charAt(3)); // 'b'
        System.out.println(s.indexOf('c')); // 6
        System.out.println(s.indexOf('c', 10)); // 15
        System.out.println(s.indexOf("bbb")); // 3
        System.out.println(s.indexOf("bbb", 10)); // 12
        System.out.println(s.lastIndexOf('c')); // 17
        System.out.println(s.lastIndexOf('c', 10)); // 8
        System.out.println(s.lastIndexOf("bbb")); // 12
        System.out.println(s.lastIndexOf("bbb", 10)); // 3
}

注意:

上述方法都是實(shí)例方法,通過(guò)對(duì)象引用調(diào)用。

三. 轉(zhuǎn)化

1. 數(shù)值和字符串轉(zhuǎn)化

static String valueof() 數(shù)值轉(zhuǎn)字符串

Integer.parseInt() 字符串整形

Double.parseDouble() 字符串轉(zhuǎn)浮點(diǎn)型

public class Test {
    public static void main(String[] args) {
        // 值轉(zhuǎn)字符串
        String s1 = String.valueOf(1234);
        String s2 = String.valueOf(12.34);
        String s3 = String.valueOf(true);
        String s4 = String.valueOf(new Student("Hanmeimei", 18));
        
        System.out.println(s1);
        System.out.println(s2);
        System.out.println(s3);
        System.out.println(s4);
        System.out.println("=================================");
        
        // 字符串轉(zhuǎn)數(shù)字
        //Integer、Double等是Java中的包裝類(lèi)型
        int data1 = Integer.parseInt("1234");
        double data2 = Double.parseDouble("12.34");
        
        System.out.println(data1);
        System.out.println(data2);
    }
}

class Student{
    String name;
    int age;
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

執(zhí)行結(jié)果:

2. 大小寫(xiě)轉(zhuǎn)化

String toUpperCase() 轉(zhuǎn)大寫(xiě)

String toLowerCase() 轉(zhuǎn)小寫(xiě)

這兩個(gè)函數(shù)只轉(zhuǎn)換字母。

public static void main(String[] args) {
        String s1 = "hello";
        String s2 = "HELLO";
        // 小寫(xiě)轉(zhuǎn)大寫(xiě)
        System.out.println(s1.toUpperCase());
        // 大寫(xiě)轉(zhuǎn)小寫(xiě)
        System.out.println(s2.toLowerCase());
}

執(zhí)行結(jié)果:

3. 字符串和數(shù)組的轉(zhuǎn)換

char[ ] toCharArray() 字符串轉(zhuǎn)數(shù)組

new String(數(shù)組引用) 數(shù)組轉(zhuǎn)字符串

public static void main(String[] args) {
        String s = "hello";
        // 字符串轉(zhuǎn)數(shù)組
        char[] ch = s.toCharArray();
        for (int i = 0; i < ch.length; i++) {
            System.out.print(ch[i]);
        }
        System.out.println();
        // 數(shù)組轉(zhuǎn)字符串
        String s2 = new String(ch);
        System.out.println(s2);
}

執(zhí)行結(jié)果:

4. 格式化

static String format( );

public static void main(String[] args) {
        String s = String.format("%d-%d-%d", 2022, 8, 29);
        System.out.println(s);
}

執(zhí)行結(jié)果:

四. 字符串替換

使用一個(gè)指定的新的字符串替換掉已有的字符串?dāng)?shù)據(jù),可用的方法如下:

方法功能
String replaceAll(String regex, String replacement)替換所有的指定內(nèi)容
String replaceFirst(String regex, String replacement)替換首個(gè)指定內(nèi)容

代碼示例:

字符串的替換處理:

public static void main(String[] args) {
        String str = "helloworld" ;
        System.out.println(str.replaceAll("l", "_"));
        System.out.println(str.replaceFirst("l", "_"));
}

執(zhí)行結(jié)果:

注意事項(xiàng):

由于字符串是不可變對(duì)象, 替換不修改當(dāng)前字符串, 而是產(chǎn)生一個(gè)新的字符串.

五. 字符串拆分

可以將一個(gè)完整的字符串按照指定的分隔符劃分為若干個(gè)子字符串。

可用方法如下:

方法功能
String[] split(String regex)將字符串全部拆分
String[] split(String regex, int limit)將字符串以指定的格式,拆分為limit組

如果一個(gè)字符串中有多個(gè)分隔符,可以用"|"作為連字符.

代碼示例:

實(shí)現(xiàn)字符串的拆分處理

public static void main(String[] args) {
        String str = "hello world hello rong";
        String[] result = str.split(" ") ; // 按照空格拆分
        for(String s: result) {
            System.out.println(s);
        }

        System.out.println("==============");

        String str1 = "xin&xin=xiang&rong";
        String[] str2 = str1.split("&|=");//按照=和&拆分
        for(String s: str2) {
            System.out.println(s);
        }
}

執(zhí)行結(jié)果:

代碼示例:

字符串的部分拆分

public static void main(String[] args) {
        String str = "hello world hello rong" ;
        String[] result = str.split(" ",2) ;
        for(String s: result) {
            System.out.println(s);
        }  
}

執(zhí)行結(jié)果:

有些特殊字符作為分割符可能無(wú)法正確切分, 需要加上轉(zhuǎn)義.

字符"|“,”*“,”+“,”."都得加上轉(zhuǎn)義字符,前面加上 “” .

而如果是 “” ,那么就得寫(xiě)成 “\” ; 使用split來(lái)切分字符串時(shí),遇到以反斜杠\作為切分的字符串,split后傳入的內(nèi)容是\\,這么寫(xiě)是因?yàn)榈谝缓偷谌莻€(gè)斜杠是字符串的轉(zhuǎn)義符。轉(zhuǎn)義后的結(jié)果是\,split函數(shù)解析的不是字符串而是正則,正則表達(dá)式中的\結(jié)果對(duì)應(yīng)\,所以分隔反斜杠的時(shí)候要寫(xiě)四個(gè)反斜杠。

代碼示例:

拆分IP地址

public static void main(String[] args) {
        String str = "192.168.1.1" ;
        String[] result = str.split("\\.") ;
        for(String s: result) {
            System.out.println(s);
        }
}

執(zhí)行結(jié)果:

代碼中的多次拆分:

ppublic static void main(String[] args) {
        //字符串多次拆封
        String str = "xin&xin=xiang&rong";
        String[] str1 = str.split("&");
        for (int i = 0; i < str1.length; i++) {
            String[] str2 = str1[i].split("=");
            for (String x:str2) {
                System.out.println(x);
            }
        }

        String s = "name=zhangsan&age=18" ;
        String[] result = s.split("&") ;
        for (int i = 0; i < result.length; i++) {
            String[] temp = result[i].split("=") ;
            System.out.println(temp[0]+" = "+temp[1]);
        }
}

執(zhí)行結(jié)果:

六. 字符串截取

從一個(gè)完整的字符串之中截取出部分內(nèi)容??捎梅椒ㄈ缦?:

方法功能
String substring(int beginIndex)從指定索引截取到結(jié)尾
String substring(int beginIndex, int endIndex)截取部分內(nèi)容

代碼示例:

public static void main(String[] args) {
        String str = "helloworld" ;
        System.out.println(str.substring(5));
        System.out.println(str.substring(0, 5));
}

執(zhí)行結(jié)果:

注意事項(xiàng):

索引從0開(kāi)始

注意前閉后開(kāi)區(qū)間的寫(xiě)法, substring(0, 5) 表示包含 0 號(hào)下標(biāo)的字符, 不包含 5 號(hào)下標(biāo),即(0,4)

七. 其他操作方法

1. String trim()

去掉字符串中的左右空格,保留中間空格

trim 會(huì)去掉字符串開(kāi)頭和結(jié)尾的空白字符(空格, 換行, 制表符等).

示例代碼:

public static void main(String[] args) {
        String str = "      hello world      " ;
        System.out.println("["+str+"]");
        System.out.println("["+str.trim()+"]");
}

執(zhí)行結(jié)果:

2. boolean isEmpty ()

isEmpty() 方法用于判斷字符串是否為空

示例代碼:

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

執(zhí)行結(jié)果:

3. int length()

用于求字符串的長(zhǎng)度

示例代碼:

public static void main(String[] args) {
        String str = "xinxinxiangrong";
        System.out.println(str.length());
}

執(zhí)行結(jié)果:

4. 判斷字符串開(kāi)頭結(jié)尾

boolean startsWith(String prefix) 判斷字符串是否以某個(gè)字符串開(kāi)頭的

boolean endWith(String sufix) 判斷字符串是否以某個(gè)字符串結(jié)尾的

示例代碼:

public static void main(String[] args) {
        String str = "xinxinxianrong";
        System.out.println(str.startsWith("xin"));
        System.out.println(str.endsWith("rong"));
}

執(zhí)行結(jié)果:

5. boolean contains(String str)

判斷字符串中是否包含某個(gè)字符串

示例代碼:

public static void main(String[] args) {
        String str = "xinxinxianrong";
        System.out.println(str.contains("inx"));
}

執(zhí)行結(jié)果:

以上就是Java中String類(lèi)常用方法總結(jié)詳解的詳細(xì)內(nèi)容,更多關(guān)于Java String類(lèi)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Java日常練習(xí)題,每天進(jìn)步一點(diǎn)點(diǎn)(57)

    Java日常練習(xí)題,每天進(jìn)步一點(diǎn)點(diǎn)(57)

    下面小編就為大家?guī)?lái)一篇Java基礎(chǔ)的幾道練習(xí)題(分享)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧,希望可以幫到你
    2021-08-08
  • MyBatis中多對(duì)一和一對(duì)多數(shù)據(jù)的處理方法

    MyBatis中多對(duì)一和一對(duì)多數(shù)據(jù)的處理方法

    這篇文章主要介紹了MyBatis中多對(duì)一和一對(duì)多數(shù)據(jù)的處理,本文通過(guò)示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-01-01
  • 深入了解Java.Util.Date詳情

    深入了解Java.Util.Date詳情

    這篇文章主要介紹了Java.Util.Date,很少有類(lèi)能像java.util.Date那樣在堆棧溢出方面引起如此多的類(lèi)似問(wèn)題,關(guān)于具體原因下文內(nèi)容詳細(xì)介紹,需要的朋友可以參考一下
    2022-06-06
  • @RequestAttribute和@RequestParam注解的區(qū)別及說(shuō)明

    @RequestAttribute和@RequestParam注解的區(qū)別及說(shuō)明

    這篇文章主要介紹了@RequestAttribute和@RequestParam注解的區(qū)別及說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-05-05
  • 使用Java如何將文本復(fù)制到剪貼板

    使用Java如何將文本復(fù)制到剪貼板

    這篇文章主要介紹了使用Java如何將文本復(fù)制到剪貼板問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-05-05
  • Spring Boot中的@ConfigurationProperties注解解讀

    Spring Boot中的@ConfigurationProperties注解解讀

    在SpringBoot框架中,@ConfigurationProperties注解是處理外部配置的強(qiáng)大工具,它允許開(kāi)發(fā)者將配置文件中的屬性自動(dòng)映射到Java類(lèi)的字段上,實(shí)現(xiàn)配置的集中管理和類(lèi)型安全,通過(guò)定義配置類(lèi)并指定前綴,可以將配置文件中的屬性綁定到Java對(duì)象
    2024-10-10
  • 超全面的SpringBoot面試題含答案

    超全面的SpringBoot面試題含答案

    這篇文章主要收錄了44道面試中經(jīng)常被問(wèn)的SpringBoot問(wèn)題,不管你是正在求職的新手還是已經(jīng)工作很久的高手,這篇關(guān)于SpringBoot的面試題總結(jié)一定會(huì)讓你有新的理解,讓我們一起來(lái)看看吧
    2023-03-03
  • Mybatis逆向工程時(shí)失敗問(wèn)題及解決

    Mybatis逆向工程時(shí)失敗問(wèn)題及解決

    這篇文章主要介紹了Mybatis逆向工程時(shí)失敗問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-11-11
  • 大廠(chǎng)面試???快速排序冒泡排序算法

    大廠(chǎng)面試???快速排序冒泡排序算法

    快速排序由于排序效率在同為O(N*logN)的幾種排序方法中效率較高,因此經(jīng)常被采用,再加上快速排序思想----分治法也確實(shí)實(shí)用,因此很多軟件公司的筆試面試,包括像BAT、字節(jié)、美團(tuán)等知名IT公司都喜歡考查快速排序原理和手寫(xiě)源碼
    2021-08-08
  • Spring中的MultipartFile詳解

    Spring中的MultipartFile詳解

    這篇文章主要介紹了Spring中的MultipartFile詳解,隨著Spring框架的崛起,使用Spring框架中的MultipartFile來(lái)處理文件也是件很方便的事了,今天就為大家?guī)?lái)剖析MultipartFile的神秘面紗,需要的朋友可以參考下
    2024-01-01

最新評(píng)論

宜良县| 航空| 新昌县| 深水埗区| 南华县| 泽州县| 清苑县| 沐川县| 泸水县| 乌拉特前旗| 洱源县| 无棣县| 政和县| 盐源县| 屏东县| 淮滨县| 昌都县| 张家口市| 东明县| 江川县| 沙田区| 仙桃市| 宝山区| 平湖市| 宜黄县| 怀集县| 洪江市| 天津市| 论坛| 阿拉善右旗| 黔西县| 富平县| 贵德县| 乌鲁木齐县| 启东市| 诸暨市| 阜宁县| 兴和县| 报价| 中卫市| 阳朔县|