字符串和正则表达式习题

本文探讨了字符串的验证、生成、替换及处理技巧,包括条形码验证、随机字符串生成、字符替换、字符串统计与截取、字符数组操作、身份证号生日提取、手机号码与固话号码提取等。同时,对比了String与StringBuffer在性能上的差异,并展示了Java编程中的一些基础概念和异常处理。
摘要由CSDN通过智能技术生成
  1. 验证ean-13条码的验证码是否正确

    String code = “6921168509256”;

    取前12位的奇数位的和

    取前12位的偶数位的和

    将"奇数位和"与"偶数位和的三倍"相加求和

    取和的个位数,然后用10减去这个个位数,相减的结果就是条码的验证码

    如果条码的第13位数字和这个验证码相同就说明验证码正确

public class Work1 {
    public static void main(String[] args) {
        String code = "6921168509256";

        int temp = test(code);//验证码

        System.out.println(temp == code.charAt(12) - '0' ? "验证码正确" : "验证码错误");
    }

    public static int test(String code) {
        int sum1 = 0;//前12位的奇数位的和
        int sum2 = 0;//前12位的偶数位的和

        int sum = 0;

        for (int i = 0; i < 12; i = i + 2) {
            sum1 += (code.charAt(i) - '0');   //数字字符-数字字符=整数
            sum2 += (code.charAt(i + 1) - '0');
        }
        sum = sum1 + sum2 * 3;
        return 10 - sum % 10;
    }
}
  1. 【难】给定一个长度,生成一个指定长度的字符串,这个字符串由随机的字母、数字或下划线组成。(不用必须同时包含字母、数字、下划线)
import java.util.Random;
import java.util.Scanner;

public class Work2 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入字符串的长度:");
        int len = scanner.nextInt();
        test(len);
    }

    public static void test(int len) {
        Random random = new Random();
        int i = 0;

        while (i < len) {
            int k = (int) random.nextInt(58) + 65;
            /**
             * ASCII表中每个字母和数字都有对应的编号
             * 65~90 A~Z
             * 95 下划线
             * 97~122 a~Z
             * 48~57 0~9
             */
            if (k >= 48 && k <= 57 || k >= 65 && k <= 90 || k == 95 || k >= 97 && k <= 122) {
                System.out.print((char) k);
                i++;
            }
        }
    }
}
  1. 【中】将一个字符串中最后一次出现的指定字符替换成大小写翻转的字符。

replace(“hello”, ‘l’) -> helLo
replace(“HELLO”, ‘L’) -> HELlO

public class Work3 {
    public static void main(String[] args) {
        String str = "hello";
        System.out.println(replace(str,'l'));
    }

    public static String replace(String str,char c){
        StringBuffer str1 = new StringBuffer();
        str1.append(str.substring(0,(str.lastIndexOf(c))));
        char ch = (char)str.substring(str.lastIndexOf(c),str.lastIndexOf(c)+1).charAt(0);

        if(ch>='a'&& ch<='z'){
            ch = (char)(ch-32);
        }else if(ch>='A'&& ch<='Z'){
            ch = (char)(ch+32);
        }else
            ch = ch;

        str1.append(ch);
        str1.append(str.substring(str.lastIndexOf(c)+1));
        return str1.toString();
    }
}
  1. 已知字符串:“this is a test of java”. 按要求执行以下操作:

    (1) 【简】统计该字符串中字母s出现的次数

    (2) 【简】取出子字符串"test"

    (3) 【简】将本字符串复制到一个字符数组Char[] str中.

    (4) 【中】将字符串中每个单词的第一个字母变成大写, 输出到控制台。

    import java.util.Arrays;
    public class Work4 {
        public static void main(String[] args) {
            String str = "this is a test of java";
    
            //(1) 【简】统计该字符串中字母s出现的次数
            int n = (str.split("s")).length-1;
            System.out.println("字母s出现的次数"+n);
    
            //(2) 【简】取出子字符串"test"
            String str1 = str.substring(10,14);
            System.out.println("取出字符串"+str1);
    
            //(3) 【简】将本字符串复制到一个字符数组Char[] str中.
            char[] str2 = str.toCharArray();
            System.out.println(Arrays.toString(str2));
    
            //(4) 【中】将字符串中每个单词的第一个字母变成大写,输出到控制台。
            test(str);
        }
    
        public static void test(String str){
            String[]a=str.split(" ");
            for (String string : a) {
                String c = string.toUpperCase();//将所有单词都转为大写
                char d = c.charAt(0);//取大写单词的首字母
                System.out.print(d + string.substring(1) + " ");//拼接
            }
        }
    }
    
  2. 【中】设计一个方法,提取一个身份证号码中的生日部分。身份证号的验证规则,只需要验证前17位是数字,最后一位可以数字或者X即可。

  public class CheckingId {
      public static void main(String[] args) {
          String id = "165165197001012563";
          if(isId(id)){
              System.out.println("生日部分为"+id1.substring(10,14));
          }else {
              System.out.println("身份证格式有误");
          }
          System.out.println(getBirthdayById(id1));
  
      }
      public static boolean isId(String id){
          String checking = "\\d{17}[\\d|x|X]";
          return id.matches(checking);
      }
      public static String getBirthdayById(String id){
  
          String regex = "\\d{6}(\\d{8})\\d{3}[\\dX]";
          return id.replaceAll(regex, "$1");
      }
  }
  1. 【中】设计一个方法,将如下字符串中的所有手机号码和固话号码提取出来,存入一个数组返回。

    1.手机号码的校验: 首位是1,第二位是 3579,后面都是数字

    2.固化校验: 区号-号码,其中区号3或4位,号码7位,且首位不能是0

    3.待提取数据的字符串:

    17788889999-010-9988776-19822883322-0398-8976564-16722882288-0922-78906543-15490876845-010-99821123
    
    public class Work7 {
        public static void main(String[] args) {
            System.out.println(Arrays.toString(getPhones()));
        }
        private static String[] getPhones() {
            String data = "17788889999-010-9988776-19822883322-0398-8976564-16722882288-0922-78906543-15490876845-010-99821123";
            Pattern pattern = Pattern.compile("1[3579]\\d{9}|\\d{3,4}-[1-9]\\d{6}");
            Matcher matcher = pattern.matcher(data);
            StringBuilder builder = new StringBuilder();
            while (matcher.find()) {
                builder.append(matcher.group()).append(", ");
            }
            return builder.toString().split(", ");
        }
    
    
  2. 比较String和StringBuffer在大字符串操作方面的性能差异, 比如增加1万个单词,比较各自所用的时间

    public void Work8() {
            //String
            long stringBeginTime = System.currentTimeMillis();
            String s = "";
            for (int i = 0; i <= 10000; i++) {
                s += "hello";
            }
            long stringEndTime = System.currentTimeMillis();
    
            //StringBuffer
            long stringBufferBeginTime = System.currentTimeMillis();
            StringBuffer stringBuffer = new StringBuffer();
            for (int i = 0; i <= 10000; i++) {
                stringBuffer.append("world");
            }
            long stringBufferEndTime = System.currentTimeMillis();
    
            System.out.println("String运行时间为"+(stringEndTime-stringBeginTime));
            System.out.println("StringBuffer运行时间为"+(stringBufferEndTime-stringBufferBeginTime));
        }
    

    附加题(选择题)

    1. 下面关于java.lang.Exception类的说法正确的是()			    A
    A 继承自Throwable 				B Serialable 			C不记得,反正不正确 
        
    2. 下面程序的运行结果是( )									B
    String str1 = "hello"; 
    String str2 = "he" + new String("llo"); 
    System.out.println(str1 == str2);
    A true 			B false 
        
    3. 下列说法正确的有() 										 C
    Aclass中的constructor不可省略 
    B. constructor必须与class同名,但方法不能与class同名 
    C. constructor在一个对象被new时执行
    D.一个class只能定义一个constructor 
        
    4. 下列说法正确的是() 										C
    A LinkedList继承自List 
    B AbstractSet继承自Set 
    C HashSet继承自AbstractSet 
    D WeakMap继承自HashMap 
        
    5. 存在使i + 1 < i的数吗() byte a = 127 a+1 = -128 		   A
    A 存在 			B 不存在
                       
    6. 0.6332的数据类型是() 									  B
    A float 
    B double 
    C Float 
    D Double 
                       
     7. 下面哪个流类属于面向字符的输入流( ) 可以先不写 				D
    A BufferedWriter 
    B FileInputStream 
    C ObjectInputStream 
    D InputStreamReader
                       
    8. Java接口的修饰符可以为() 								   D
    A private 
    B protected 
    C final 
    D abstract 
                       
    9. 不通过构造函数也能创建对象吗() 							B
    AB11. 下面程序能正常运行吗() 								  A
    public class NULL { 
        public static void haha(){ 
            System.out.println("haha"); 
        }
        public static void main(String[] args) { 
            ((NULL)null).haha(); 
        } 
    }
    A 能正常运行 			B 不能 
                       
    12. 写出下面程序的运行结果: 
    class HelloA { 
        public HelloA() { 
            System.out.println("HelloA");4
        }
        { System.out.println("I'm A class"); }3 
            
        static { System.out.println("static A"); }1 
    }
    
    public class HelloB extends HelloA { 
        public HelloB() {//优先调用父类的构造方法
            System.out.println("HelloB");6 
        }
        { System.out.println("I'm B class"); }5
        static { System.out.println("static B"); }2
            
        public static void main(String[] args) { 
            new HelloB(); 
        } 
    }
    
    结果:static A
    	static B
    	I'm A class
    	HelloA
    	I'm B class
    	HelloB
                       
    13. 下面代码的运行结果为:() 										C
    import java.io.*; 
    import java.util.*; 
    public class foo{ 
        public static void main (String[] args){ 
            String s; 
            System.out.println("s=" + s); 
        } 
    }
    A 代码得到编译,并输出“s=B 代码得到编译,并输出“s=nullC 由于String s没有初始化,代码不能编译通过 
    D 代码得到编译,但捕获到 NullPointException异常 
                       
    14. System.out.println("5" + 2);的输出结果应该是()。				A
    A 52 
    B 7 
    C 2 
    D 5 
                       
    15. 指出下列程序运行的结果 () 										B
    public class Example { 
        String str = new String("good"); 
        char[] ch = { 'a', 'b', 'c' }; 
        public static void main(String args[]) {
            Example ex = new Example(); 
            ex.change(ex.str, ex.ch); 
            System.out.print(ex.str + " and "); 
            System.out.print(ex.ch);
        }
        public void change(String str, char ch[]) { 
            str = "test ok";
            ch[0] = 'g'; 
        } 
    } 
    A、 good and abc 
    B、 good and gbc 
    C、 test ok and abc
    D、 test ok and gbc 
                       
    16. 下列哪种异常是检查型异常,需要在编写程序时声明 () 				C
    A NullPointerException 
    B ClassCastException 
    C FileNotFoundException
    D IndexOutOfBoundsException 
                       
    17. 下面的方法,当输入为2的时候返回值是多少?()						D
        public static int getValue(int i) {
            int result = 0;
            switch (i) { 
                case 1: 
                    result = result + i; 
                case 2: 
                    result = result + i * 2;
                case 3:
                    result = result + i * 3; 
            }
            return result; 
        } 
    A 0 		B 2 		C 4 			D10 
                       
    18. 选项中哪一行代码可以替换题目中//add code here而不产生编译错误?()	 A
    public abstract class MyClass { 
        public int constInt = 5; 
        //add code here
        public void method() { 
        } 
    }
    A public abstract void method(int a); 
    B constInt = constInt + 5; 
    C public int method(); 
    D public abstract void anotherMethod() {} 
                       
    19.下面是PeopleChild类的定义和构造方法,每个构造方法都输出编号。在执行new Child("mike")的时候都有哪些构造方法被顺序调用?请选择输出结果 ( ) 										D
    class People { 
        String name; public People() {
            System.out.print(1); 
        }
        public People(String name) { 
            System.out.print(2); 
            this.name = name; 
        } 
    }
                       
    class Child extends People { 
        People father; 
        public Child(String name) {//super(); 
            System.out.print(3); 
            this.name = name; 
            father = new People(name + ":F"); 
        }
        public Child() { 
            System.out.print(4); 
        } 
    }
    A 312 		B 32 		C 432 		D 132 
                       
     20.写出下面程序的运行结果是什么?             
    public class Dervied extends Base { 
        private String name = "dervied"; 
        public Dervied() { 
            
            tellName(); 
            printName(); 
        }
        
        public void tellName() { 
            System.out.println("Dervied tell name: " + name); 
        }
        
        public void printName() {
            System.out.println("Dervied print name: " + name); 
        }
        public static void main(String[] args){ 
            new Dervied();//1.执行父类的构造方法 2.给自己的成员变量赋值 3。调 用构造方法中的调用的方法 
        } 
    }
                       
    class Base { 
        private String name = "base"; 
        public Base() { 
            tellName(); 
            printName(); 
        }
        public void tellName() { 
            System.out.println("Base tell name: " + name); 
        }
        public void printName() { 
            System.out.println("Base print name: " + name);
        } 
    }
    
    运行结果:Dervied tell name: null 
            Dervied print name: null 
            Dervied tell name: dervied 
            Dervied print name: dervied 
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值