主要功能方法举例
1.判断功能
验证键盘输入QQ号码是否格式正确(体现正则表达式的优势)
格式要求:非0开头,5-11位
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入QQ号码:");
String s = sc.next();
//boolean falg = checkQQNumber(s);//if语句判断qq号码格式
boolean falg = checkQQNumber1(s);//正则表达式判断qq号码格式
if (falg == true){
System.out.println("输入号码正确");
}else
System.out.println("输入号码错误");
}
private static boolean checkQQNumber(String s) {
boolean flag = false;
if (s.length()>= 5&&s.length()<= 12){
if (!s.startsWith("0")){
for (int i = 1; i < s.length(); i++) {
char c = s.charAt(i);
if (!(c>='0'&&c<='9')){
return flag;
}
}
flag = true;
}
}
return flag;
}
private static boolean checkQQNumber1(String s) {
boolean matches = s.matches("[1-9][0-9]{4,11}");
return matches;
}
2.分割功能
将字符串"11 22 88 99 77 66 55"排序后输出
输出结果:"11 22 55 66 77 88 99"
public class Split {
public static void main(String[] args) {
String s = "11 22 88 99 77 66 55";
String[] strings = s.split(" ");//根据空格分割字符串
int[] ints = new int[strings.length];
//将分割出的字符串数组元素放进int数组中用来排序
for (int i = 0; i < ints.length; i++) {
ints[i] = Integer.parseInt(strings[i]);
}
//排序
Arrays.sort(ints);
//再将排序好的元素组成字符串输出
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < ints.length; i++) {
stringBuilder.append(ints[i]).append(" ");
}
System.out.println(stringBuilder.toString().trim());
}
}
3.替换功能
去除字符串中出现的空格
String str="abc abcabcabc abc abc";
String s = str.replaceAll(" +", "");
System.out.println(s);//输出结果:abcabcabcabcabcabc