Java 中的 String 類常用方法

來源:互聯網
上載者:User

標籤:str   com   方法   ring   nbsp   pre   tin   mail   並且   

字串廣泛應用在Java編程中,在Java中字串屬於對象,String 類提供了許多用來處理字串的方法,例如,擷取字串長度、對字串進行截取、將字串轉換為大寫或小寫、字串分割等。

 

String 類的常用方法:

 

注意事項:

1. 字串 str 中字元的索引從0開始,範圍為 0 到 str.length()-1

2. 使用 indexOf 進行字元或字串尋找時,如果匹配返回位置索引;如果沒有匹配結果,返回 -1

3. 使用 substring(beginIndex , endIndex) 進行字串截取時,包括 beginIndex 位置的字元,不包括 endIndex 位置的字元

 “==” 和 equals() 有什麼區別

==: 判斷兩個字串在記憶體中首地址是否相同,即判斷是否是同一個字串對象

equals(): 比較儲存在兩個字串對象中的內容是否一致

 

 

 

 

執行個體:判斷 Java 檔案名稱及郵箱格式是否正確

public class test {    public static void main(String[] args) {        // Java檔案名稱        String fileName = "HelloWorld.java";         // 郵箱        String email = "[email protected]";                // 判斷.java檔案名稱是否正確:合法的檔案名稱應該以.java結尾              //擷取檔案名稱中最後一次出現"."號的位置        int index = fileName.lastIndexOf(‘.‘);                // 擷取檔案的尾碼        String prefix =fileName.substring(index+1, fileName.length());                // 判斷必須包含"."號,且不能出現在首位,同時尾碼名為"java"        if (index!=-1&&index!=0&&prefix.equals ("java") ) {            System.out.println("Java檔案名稱正確");        } else {            System.out.println("Java檔案名稱無效");        }        // 判斷郵箱格式是否正確:合法的郵箱名中至少要包含"@", 並且"@"是在"."之前                 // 擷取郵箱中"@"符號的位置        int index2 = email.indexOf(‘@‘);                // 擷取郵箱中"."號的位置        int index3 = email.lastIndexOf(‘.‘);                // 判斷必須包含"@"符號,且"@"必須在"."之前        if (index2 != -1 && index3 > index2) {            System.out.println("郵箱格式正確");        } else {            System.out.println("郵箱格式無效");        }    }}

 

  

 

 

 

Java 中的 String 類常用方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.