分割功能
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 }