美文网首页
Java学习笔记 - 第020天

Java学习笔记 - 第020天

作者: 迷茫o | 来源:发表于2016-12-23 19:53 被阅读0次

    每日要点

    字符串Sring

    Sting 是不变字符串 对字符串的修改操作会产生新的字符串对象
    而不是修改原来的对象

    例子1:

            String str1 = "abc";
            String str2 = new String("abc");
            System.out.println(str1 == str2);
            String str3 = new String("abc");
            String str4 = "ab" + "c";
            System.out.println(str2 == str3);
            System.out.println(str1 == str4);
            // 两个面试题:
            // 1.输出str5的结果
            // 2.下面的语句总共创建了几个字符串对象
            String str5 = 1 + 2 + "a" + "b" + 3 + 4;
            System.out.println(str5);
            String str6 = "hello, world";
            // length() - 获得字符串的长度(字符数量)
            System.out.println(str6.length());
            // charAt() - 获取指定位置的字符
            char ch = str6.charAt(1);
            System.out.println(ch);
            // compareTo() / equals() - 字符串比较
            // compareToIgnoreCase()
            System.out.println(str6.compareTo("Hello, world"));
            System.out.println(str6.compareToIgnoreCase("Hello, world"));
            System.out.println(str6.equals("Hello, world"));
            System.out.println(str6.equalsIgnoreCase("Hello, world"));
            // 字符串链接
            String str7 = str6.concat("! Goodbye!");
            System.out.println(str6);
            System.out.println(str7);
            // - 用新内容替换字符串中指定内容
            str7 = str7.replaceAll("Good", "Fuck");
            str7 = str7.replace("o", "@");
            System.out.println(str7);
            String str8 = "床前明月光,疑是地上霜,举头望明月,低头思故乡";
            // 将字符串用指定的字符拆分成多个字符串
            String[] strsArray = str8.split(",");
            for (String str : strsArray) {
                System.out.println(str);
            }
            // 从字符串中取出指定范围的子串
            String str9 = str8.substring(7);
            System.out.println(str9);
            String str10 = str8.substring(6, 11);
            System.out.println(str10);
            String str11 = "   hello   world   ";
            // 去掉字符串左右两端的空格
            System.out.println(str11.trim());
            int a = 123;
            String str12 = "" + a;
            // 静态方法 - 将基本数据类型转换成对应的字符串
            String str13 = String.valueOf(a);
            System.out.println(str12 == str13);
            System.out.println(str12.equals(str13));
            System.out.println(str12);
            System.out.println(String.valueOf(str13));
            // 检查字符串是否以指定的内容结尾
            String str14 = "program.exe";
            System.out.println(str14.endsWith("exe"));
            // 检查字符串是否以指定的内容开头
            String str15 = "http://www.baidu.com";
            System.out.println(str15.startsWith("http://"));
    

    StingBuffer和StringBuilder

    StingBuffer和StringBuilder代表可变字符串
    对字符串做修改时不会创建新的字符串对象
    StringBuffer是线程安全的 - 多个线程可以操作同一个StringBuffer对象
    StringBuilder是线程不安全的 - 多个线程同时操作StringBuilder时会发生错误
    Stringbuilder是Java 5引入的可变字符串类型 它拥有更好的性能
    例子2

    //      StringBuffer sb = new StringBuffer("hello");
            StringBuilder sb = new StringBuilder("hello");
            // 在字符串末尾追加新内容
            sb.append(" world!");
            sb.append(" goodbye!");
            // 在字符串指定位置插入新内容
            sb.insert(5, " good");
            sb.insert(0, "hi! ");
            System.out.println(sb);
            // 删除指定位置的字符
            sb.deleteCharAt(10);
            // 删除指定范围的字符
            // 第一个参数是开始索引(从0数)
            // 第二个参数是结束索引(从1数)
            sb.delete(0, 9);
            System.out.println(sb);
            // 字符串内容反转
            sb.reverse();
            System.out.println(sb);
            // 修改字符串指定位置的字符
            sb.setCharAt(5, '#');
            System.out.println(sb);
    

    结论

    如果需要频繁的修改一个字符串请不要使用Sring因为每次修改都有可能创建
    新的字符串对象 所以在这种场景下应该使用StingBuilder或者StringBuffer

    /*      String str = "";
            long start = System.nanoTime();
            for (int i = 0; i < 100000; i++) {
                str += 'a';
            }
            long end = System.nanoTime();
            System.out.println((end - start) / 1e9 + "s");*/
    //      StringBuffer str = new StringBuffer();
            StringBuilder str = new StringBuilder();
            long start = System.nanoTime();
            for (int i = 0; i < 10000000; i++) {
                str.append('a');
            }
            long end = System.nanoTime();
            System.out.println((end - start) / 1e9 + "s");
    

    练习

    1.窗口滚动字段
    public class MyFrame extends JFrame {
        
        public MyFrame() {  
            
            this.setTitle("练习");
            this.setSize(350, 100);
            this.setResizable(false);
            this.setLocationRelativeTo(null);
            this.setDefaultCloseOperation(EXIT_ON_CLOSE);
            
            JLabel jLabel = new JLabel("欢迎来到成都千锋JavaEE1601班              ");
            jLabel.setFont(new Font("微软雅黑", Font.PLAIN, 18));
            this.add(jLabel);
            
            Timer timer = new Timer(200, e -> {
                // jLabel = new JLabel("hello"); // compiler error
    //          String startStr = str.substring(0, 1);
    //          jLabel.setText(str.substring(1) + startStr);
                
                 String str = jLabel.getText();
                 str = str.substring(1) + str.charAt(0);
                 jLabel.setText(str);
                
    /*          StringBuilder sb = new StringBuilder(jLabel.getText());
                char ch = sb.charAt(0);
                sb.deleteCharAt(0).append(ch);
                jLabel.setText(sb.toString());*/
            });
            timer.start();
        }
        
        @Override
        public void paint(Graphics g) {
            super.paint(g);
        }
        
        public static void main(String[] args) {
            new MyFrame().setVisible(true);
        }
    }
    

    正则表达式

    正则表达式 - regular expression
    定义字符串的匹配模式
    例子1:

        // [] 任取其一 {}一组 
        public static void main(String[] args) {
            String tel = "13821424679";
            // boolean isValid = str.matches("1[3478][0-9]{9}");
            boolean isValid = tel.matches("1[3478]\\d{9}");
            System.out.println(isValid);
            
            String qq = "123421";
            boolean isValidQQ = qq.matches("[1-9][0-9]{4,11}");
            System.out.println(isValidQQ);
            
            String username = "sadwqf";
            // boolean isValidUid = username.matches("[a-zA-Z0-9_]{6,20}");
            // boolean isValidUid = username.matches("[^a-zA-Z0-9_]{6,20}");
            boolean isValidUid = username.matches("\\w{6,20}");
            // boolean isValidUid = username.matches("\\W{6,20}");
            System.out.println(isValidUid);
            
            String email = "jackfrued@126.com";
            System.out.println(email.matches("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$"));
            
            String msg = "操你大爷, 日你二爷, 干你三爷, f U C k你四爷";
            msg = msg.replaceAll("[操日干]|[fF]\\s*[Uu]\\s*[Cc]\\s*[Kk]\\s*", "*");
            System.out.println(msg);
            
            String sentence = "You go your way, I will go mine!";
            String words[] = sentence.split("[\\s,!]");
            for (String word : words) {
                System.out.println(word);
            }
        }
    

    例子2:

            Pattern.matches("\\w{6,20}", "adswq");
            Pattern pattern = Pattern.compile("a*b", Pattern.CASE_INSENSITIVE);
            Matcher matcher = pattern.matcher("BaabaaaBaBaaaaaba");
            while(matcher.find()) {
                System.out.println(matcher.group());
            }
    

    练习:写一个方法,生成指定长度的验证码
    foo(6) ==> "89dsv8"
    foo(4) ==> "T9ax"

    工具类:

    public final class MyUtil {
        private static final String CHARS = "abcdefghijklmnopqrstuvwxyzABVDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        private MyUtil() {
            throw new AssertionError();
        }
        
        public static String generateVC(int len) {
            
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < len; i++) {
                int randomIndex = (int) (Math.random() * CHARS.length());
                char ch = CHARS.charAt(randomIndex);
                sb.append(ch);
            }
            return sb.toString();
        }
    }
    

    测试:

            for (int i = 0; i < 10; i++) {
                System.out.println(MyUtil.generateVC(10));
            }
    

    作业

    写一个方法,生成指定长度的验证码
    foo(6) ==> "89dsv8"
    foo(4) ==> "T9ax"
    发一个消息 ,把消息加密、解密 凯撒密码

        public static String getCode(int num) {
            String code ="";
            int i = 0;
            while (i < num) {
                int randomNum = (int) (Math.random() * 75 + 48);
                String ch = (char) randomNum + "";
                boolean isValid = ch.matches("[a-zA-Z0-9]");
                if (isValid) {
                    code += ch; 
                    i ++;
                }
            } 
            return code;
        }
    
        public static String CaesarEncrypt(String msg) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < msg.length(); i++) {
                sb.append((char) (msg.charAt(i) + 3));
            }
            return sb.toString();
        }
        public static String CaesarDecrypt(String msg) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < msg.length(); i++) {
                sb.append((char) (msg.charAt(i) - 3));
            }
            return sb.toString();
        }
        public static void main(String[] args) {
            String code = getCode(6);
            System.out.println(code);
            System.out.println(CaesarEncrypt("五大服务器"));
            System.out.println(CaesarDecrypt(CaesarEncrypt("asafwq")));
        }
    

    相关文章

      网友评论

          本文标题:Java学习笔记 - 第020天

          本文链接:https://www.haomeiwen.com/subject/dcakvttx.html