String通常都會需要處理

像是切割, 替換內容, 取某段字出來

介紹如下

 

1. 官網https://docs.oracle.com/javase/tutorial/java/data/manipstrings.html

String的索引從0開始, 到長度-1為結尾

而在C語言內有結束字元\0

但在Java中並沒有看到有提及的部分

01.png

2. 而取子字串的方法如下

a. 取特定範圍 字串.substring(開頭index, 結尾index), 其中不包含結尾index那個字元

b. 取特定範圍到結尾 字串.substring(開頭index)

c. 將特定範圍轉成CharSequence回傳 字串.subSequence(開頭index, 結尾index), 其中不包含結尾index那個字元

c. 將特定範圍轉成char[]回傳 字串.toCharArray();

ex:

  String a = "0123456789";
  System.out.println(a.substring(1, 4));
  System.out.println(a.substring(1));

  CharSequence carray = a.subSequence(1, 4);
  System.out.println(carray);

02.png

3. 字串處理方法

a. 依特定符號切成各段String : 字串.split(字串)

b. 依特定符號切成各段String, 並限制段數 : 字串.split(字串, 段數) 其中如果段數等於2, 則會切成2個String

c. 而切割時如果要區分不同的符號, 可以在字串中用 | 來區分, 像是  , | ;

d. 去掉字串頭尾空白 字串.trim()

e. 將字串內容都轉大寫 字串.toLowerCase()

f. 將字串內容都轉小寫 字串.toUpperCase()

  String b = " 0,12,34,567;89'  ";
  String[] array = b.split(",|;|'", 2);
  for(String value : array){
   System.out.println(value);
  }
  System.out.println(b.trim());  
  
  String c = "abcDEFgh";
  System.out.println(c.toLowerCase());
  System.out.println(c.toUpperCase());

03.png

 

4. 字串搜尋

a. 回傳字串內第一次出現目標字元的索引 字串.indexOf(目標字元), 如果沒符合則會回傳-1 

b. 回傳字串內從後往前搜尋第一次出現目標字元的索引 字串.indexOf(目標字元), 如果沒符合則會回傳-1

c. 回傳字串內第一次出現目標字串的索引 字串.indexOf(目標字串), 如果沒符合則會回傳-1 

d. 回傳字串內從後往前搜尋第一次出現目標字串的索引 字串.indexOf(目標字串), 如果沒符合則會回傳-1

e. 回傳字串內從目標索引後第一次出現目標字串的索引 字串.indexOf(目標字串, 起始索引), 如果沒符合則會回傳-1 

f. 回傳字串內從目標索引由後往前搜尋第一次出現目標字串的索引 字串.indexOf(目標字串, 起始索引), 如果沒符合則會回傳-1

e. 判斷目標字串是否有包含特定字串 字串.contains(特定字串) 有責回傳true, 沒有則回傳false

ex:

  String d = "aaabbccdd";
  System.out.println(d.indexOf('a'));
  System.out.println(d.lastIndexOf('a'));
  System.out.println(d.indexOf("aa"));
  System.out.println(d.lastIndexOf("aa"));
  System.out.println(d.indexOf("aa", 2));
  System.out.println(d.lastIndexOf("aa", 3));
  System.out.println(d.contains("aa"));

04.png

 

5. 字串取代

a. 將字串內目標字元換成取代字元後回傳 字串.replace(目標字元, 取代字元) 

b. 將字串內目標字串換成取代字串後回傳 字串.replace(目標字串, 取代字串)

c. 將字串內目標字串換成取代字串後回傳, 但可以用表示式 字串.replace(目標字串, 取代字串)

像是replaceAll("\\d", "*") 就是將字串內的數字全部換成*

d. 將字串內目標字串換成取代字串後回傳, 只取替換第一次遇到的,  字串.replaceFirst(目標字串, 取代字串)

ex:

  String e = "aaabb123!!ccddaa";
  System.out.println(e.replace('a', 'e'));
  System.out.println(e.replace("aa", "gg"));
  System.out.println(e.replaceAll("\\d", "@@"));
  System.out.println(e.replaceFirst("aa", "gg"));

05.png  

arrow
arrow

    RX1226 發表在 痞客邦 留言(0) 人氣()