分割功能
String類的public String[] split(String regex)
根據給定正則表達式的匹配拆分此字符串。
例子:
可以用來做年齡段的篩選,比如說,我要篩選18-26之間的年齡段的人
而18-26在后台是字符串"18-26",而年齡在后端是int類型的,18,23之類的。
所以,我們要對"18-26"這個字符串進行操作:
A:分割取18 和 26,
B:把18和26轉成int類型的
C:鍵盤輸入年齡
D:對這個年齡進行判斷
a:符合這個年齡段
b:不符合這個年齡段
1 import java.util.Scanner; 2 public class NameTest { 3 4 public static void main(String[] args) { 5 //定義年齡段的搜索范圍 6 String ages = "18-26"; 7 8 //定義正則表達式的規則 9 String regex = "-"; 10 11 //調用方法,把-給分割掉 12 String[] array = ages.split(regex); 13 14 //把array的第一個數據變成int,此時array = {18,26}; 15 int startage = Integer.parseInt(array[0]); 16 //第二個數據變成int 17 int endage = Integer.parseInt(array[1]); 18 19 //鍵盤輸入年齡 20 Scanner sc = new Scanner(System.in); 21 System.out.println("請輸入年齡"); 22 int age = sc.nextInt(); 23 24 //對輸入的年齡進行判斷 25 if( age >= startage && age <= endage){ 26 System.out.println("你的年齡符合"); 27 } 28 else{ 29 System.out.println("你的年齡不符合"); 30 } 31 } 32 33 }
我有如下一個字符串:"91 27 46 38 50"
請寫代碼實現最終輸出結果是:"27 38 46 50 91"
分析:
A:定義一個字符串
B:把字符串中的空格分隔開
C:把字符串轉換成數組
D:把數組里的元素轉換成int類型
a:首先得定義一個int數組,長度跟字符串數組一樣
b:然后再把數組里的元素轉成int類型
E:給int數組進行排序
F:對排序后的數組進行拼接,轉換成字符串
G:輸出字符串
1 import java.util.Arrays; 2 public class DivisionTest3 { 3 4 public static void main(String[] args) { 5 //定義一個字符串 6 String s = "91 27 46 38 50"; 7 //直接分割開空格 8 String[] str = s.split(" "); 9 //把字符串轉換成數組 10 char[] c = s.toCharArray(); 11 //把數組里的元素轉換成int類型 12 //a:首先得定義一個int數組,長度跟字符串數組一樣 13 int[] arr = new int[str.length]; 14 //b:然后再把數組里的元素轉成int類型 15 for(int x = 0;x < str.length ; x++){ 16 arr[x] = Integer.parseInt(str[x]);//字符串數組里的元素轉成int類型 17 } 18 //E:給int數組進行排序 public static void sort(int[] a) 19 Arrays.sort(arr); 20 //F:對排序后的int數組進行拼接,轉換成字符串 21 //定義一個StringBuilder,比StringBuffer高效率 22 StringBuilder sb = new StringBuilder(); 23 for(int x = 0; x < arr.length; x++){ 24 if(x < arr.length){ 25 sb.append(arr[x]+" "); 26 } 27 } 28 //由於這樣的拼接,最后一個元素后面有空格,所以要去除空格 29 //public String trim() 返回字符串的副本,忽略前導空白和尾部空白。 30 //由於這個方法是針對字符串的,所以,得把sb轉換成字符串 31 String result = sb.toString().trim(); 32 //輸出結果 33 System.out.println("轉換后的結果是:"+result); 34 } 35 36 }
替換功能
String類的public String replaceAll(String regex,String replacement)
使用給定的 replacement 替換此字符串所有匹配給定的正則表達式的子字符串。
例子:
有些論壇的回復內容都屏蔽掉了連續出現5個數字以上的情況,改成用**代替。這個就可以設置
分析:
A:創建鍵盤錄入
B:設置方法
a:返回類型 String
b:參數列表 String
1 public class ReplaceTest1 { 2 3 public static void main(String[] args) { 4 5 //鍵盤錄入 6 Scanner sc = new Scanner(System.in); 7 System.out.println("回復:"); 8 String str = sc.nextLine(); 9 10 //調用方法 11 System.out.println("內容:"+replace(str)); 12 } 13 14 //定義方法 15 public static String replace(String str){ 16 //設置正則表達式的屏蔽規則 17 String reuslt = str.replaceAll("\\d{5,}", "***"); //數字連續出現5次或5次以上,直接用***替換掉 18 return reuslt; 19 } 20 }
