不管是給字元串賦值,還是對字元串格式化,都屬於往字元串填充內容,一旦內容填充完畢,則需開展進一步的處理。譬如一段Word文本,常見的加工操作就有查找、替換、追加、截取等等,按照字元串的處理結果異同,可將這些操作方法歸為三大類,分別說明如下。一、判斷字元串是否具備某種特征該類方法主要用來判斷字元串是否 ...
不管是給字元串賦值,還是對字元串格式化,都屬於往字元串填充內容,一旦內容填充完畢,則需開展進一步的處理。譬如一段Word文本,常見的加工操作就有查找、替換、追加、截取等等,按照字元串的處理結果異同,可將這些操作方法歸為三大類,分別說明如下。
一、判斷字元串是否具備某種特征
該類方法主要用來判斷字元串是否滿足某種條件,返回true代表條件滿足,返回false代表條件不滿足。判斷方法的調用代碼示例如下:
String hello = "Hello World. "; // isEmpty方法判斷該字元串是否為空串 boolean isEmpty = hello.isEmpty(); System.out.println("isEmpty = "+isEmpty); // equals方法判斷該字元串是否與目標串相等 boolean equals = hello.equals("你好"); System.out.println("equals = "+equals); // startsWith方法判斷該字元串是否以目標串開頭 boolean startsWith = hello.startsWith("Hello"); System.out.println("startsWith = "+startsWith); // endsWith方法判斷該字元串是否以目標串結尾 boolean endsWith = hello.endsWith("World"); System.out.println("endsWith = "+endsWith); // contains方法判斷該字元串是否包含了目標串 boolean contains = hello.contains("or"); System.out.println("contains = "+contains);
運行以上的判斷方法代碼,得到以下的日誌信息:
isEmpty = false equals = false startsWith = true endsWith = false contains = true
二、在字元串內部進行條件定位
該類方法與字元串的長度有關,要麼返回指定位置的字元,要麼返回目標串的所在位置。定位方法的調用代碼如下所示:
String hello = "Hello World. "; // length方法返回該字元串的長度 int length = hello.length(); System.out.println("length = "+length); // charAt方法返回該字元串在指定位置的字元 char first = hello.charAt(0); System.out.println("first = "+first); // indexOf方法返回目標串在該字元串中第一次找到的位置 int index = hello.indexOf("l"); System.out.println("index = "+index); // lastIndexOf方法返回目標串在該字元串中最後一次找到的位置 int lastIndex = hello.lastIndexOf("l"); System.out.println("lastIndex = "+lastIndex);
運行以上的定位方法代碼,得到以下的日誌信息:
length = 13 first = H index = 2 lastIndex = 9
三、根據某種規則修改字元串的內容
該類方法可對字元串進行局部或者全部的修改,並返回修改之後的新字元串。內容變更方法的調用代碼舉例如下:
String hello = "Hello World. "; // toLowerCase方法返迴轉換為小寫字母的字元串 String lowerCase = hello.toLowerCase(); System.out.println("lowerCase = "+lowerCase); // toUpperCase方法返迴轉換為大寫字母的字元串 String upperCase = hello.toUpperCase(); System.out.println("upperCase = "+upperCase); // trim方法返回去掉首尾空格後的字元串 String trim = hello.trim(); System.out.println("trim = "+trim); // concat方法返回在末尾添加了目標串之後的字元串 String concat = hello.concat("Fine, thank you."); System.out.println("concat = "+concat); // substring方法返回從指定位置開始截取的子串。只有一個輸入參數的substring,從指定位置一直截取到源串的末尾 String subToEnd = hello.substring(6); System.out.println("subToEnd = "+subToEnd); // 有兩個輸入參數的substring方法,返回從開始位置到結束位置中間截取的子串 String subToCustom = hello.substring(6, 9); System.out.println("subToCustom = "+subToCustom); // replace方法返回目標串替換後的字元串 String replace = hello.replace("l", "L"); System.out.println("replace = "+replace);
運行以上的內容變更方法代碼,得到以下的日誌信息:
lowerCase = hello world. upperCase = HELLO WORLD. trim = Hello World. concat = Hello World. Fine, thank you. subToEnd = World. subToCustom = Wor replace = HeLLo WorLd.
更多Java技術文章參見《Java開發筆記(序)章節目錄》