欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

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

一. String對象的比較

1. ==比較是否引用同一個對象

注意:

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

public static void main(String[] args) {
        int a = 10;
        int b = 20;
        int c = 10;
        // 對于基本類型變量,==比較兩個變量中存儲的值是否相同
        System.out.println(a == b); // false
        System.out.println(a == c); // true
        // 對于引用類型變量,==比較兩個引用變量引用的是否為同一個對象
        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類重寫了父類Object中equals方法,Object中equals默認(rèn)按照==比較,String重寫equals方法后,按照 如下規(guī)則進(jìn)行比較,比如: s1.equals(s2)

String中的equals方法分析:

public boolean equals(Object anObject) {
    // 1. 先檢測this 和 anObject 是否為同一個對象比較,如果是返回true
    if (this == anObject) {
            return true;
    }
    // 2. 檢測anObject是否為String類型的對象,如果是繼續(xù)比較,否則返回false
    if (anObject instanceof String) {
            // 將anObject向下轉(zhuǎn)型為String類型對象
            String anotherString = (String)anObject;
            int n = value.length;
            // 3. this和anObject兩個字符串的長度是否相同,是繼續(xù)比較,否則返回false
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                // 4. 按照字典序,從前往后逐個字符進(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引用的是三個不同對象,因此==比較結(jié)果全部為false
        System.out.println(s1 == s2); // false
        System.out.println(s1 == s3); // false
// equals比較:String對象中的逐個字符
// 雖然s1與s2引用的不是同一個對象,但是兩個對象中放置的內(nèi)容相同,因此輸出true
// s1與s3引用的不是同一個對象,而且兩個對象中內(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類型,而compareTo返回的是int類型。具體比較方式:

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

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

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個字符完全相同,輸出長度差值 -3
}

4. int compareToIgnoreCase(String str)

與compareTo方式相同,但是忽略大小寫進(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個字符完全相同,輸出長度差值 -3
}

二. 字符串查找

字符串查找也是字符串中非常常見的操作,String類提供的常用查找的方法,

方法功能
char charAt(int index)返回index位置上字符,如果index為負(fù)數(shù)或者越界,拋出 IndexOutOfBoundsException異常
int indexOf(int ch)返回ch第一次出現(xiàn)的位置,沒有返回-1
int indexOf(int ch, int fromIndex)從fromIndex位置開始找ch第一次出現(xiàn)的位置,沒有返回-1
int indexOf(String str)返回str第一次出現(xiàn)的位置,沒有返回-1
int indexOf(String str, int fromIndex) 從fromIndex位置開始找str第一次出現(xiàn)的位置,沒有返回-1
int lastIndexOf(int ch)從后往前找,返回ch第一次出現(xiàn)的位置,沒有返回-1
int lastIndexOf(int ch, int fromIndex)從fromIndex位置開始找,從后往前找ch第一次出現(xiàn)的位置,沒有返 回-1
int lastIndexOf(String str)從后往前找,返回str第一次出現(xiàn)的位置,沒有返回-1
int lastIndexOf(String str, int fromIndex)從fromIndex位置開始找,從后往前找str第一次出現(xiàn)的位置,沒有返 回-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í)例方法,通過對象引用調(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中的包裝類型
        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. 大小寫轉(zhuǎn)化

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

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

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

public static void main(String[] args) {
        String s1 = "hello";
        String s2 = "HELLO";
        // 小寫轉(zhuǎn)大寫
        System.out.println(s1.toUpperCase());
        // 大寫轉(zhuǎn)小寫
        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é)果:

四. 字符串替換

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

方法功能
String replaceAll(String regex, String replacement)替換所有的指定內(nèi)容
String replaceFirst(String regex, String replacement)替換首個指定內(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):

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

五. 字符串拆分

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

可用方法如下:

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

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

代碼示例:

實(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é)果:

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

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

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

代碼示例:

拆分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é)果:

六. 字符串截取

從一個完整的字符串之中截取出部分內(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開始

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

七. 其他操作方法

1. String trim()

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

trim 會去掉字符串開頭和結(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()

用于求字符串的長度

示例代碼:

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

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

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

boolean startsWith(String prefix) 判斷字符串是否以某個字符串開頭的

boolean endWith(String sufix) 判斷字符串是否以某個字符串結(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)

判斷字符串中是否包含某個字符串

示例代碼:

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

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

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

相關(guān)文章

最新評論