• 字符串


     

    字符串的综合应用:

    举个栗子:1.获取以QQ开头文件的后缀名

        public static void main(String[] args) {
            /*fileName包含多个文件名以;分割   
            任务:获取以QQ开头的文件的后缀名*/
            String fileName = "abc.java;amos.class;QQ.OMG.exe;mysql.java;jdbc.java";
            //分割字符串
            String[] names = fileName.split(";");
            for (String name : names) {
                 //判断文件名是否以QQ开头
                if(name.startsWith("QQ")) {
                    //先返回.最后出现的位置
                    int index = name.lastIndexOf(".");
                    //返回index之后的子字符串(即返回后缀名)
                    System.out.println(name.substring(index));
                }
            }
    }
    需要用到split分割字符串,判断字符串以xxx开头需要用到startsWith方法,返回最后出现的.的位置需要用到lastIndexOf方法,返回子字符串需要用到substring

    举个栗子:2.将字符串首字母大写,其余不变。

        public static void main(String[] args) {
     
            String name = "amosWong";
            String word = name.substring(0, 1).toUpperCase();
            String name2 = name.substring(1);
            System.out.println(word + name2);
    }

    举个栗子:3.判断字符串是否为空

        public static void main(String[] args) {
            //判断字符串是否为空    把" " 和 ""都看作字符串内容为空
             String str = " ";
             if(str != null && !"".equals(str.trim())) {
                 System.out.println("非空");
             }
        }

    -------------------------------------------------------------------------------------------------------------------------------------------------------------------

    可变字符串:StringBuilder和StringBuffer

     1.StringBuilder和String相互转换:

    public static void main(String[] args) {
         String name = "AmosWong";
         //转换为StringBuilder
         StringBuilder sb1 = new StringBuilder(name);
         System.out.println(sb1);
         //转换为字符串
         sb1.toString();
         
        }

    2.append的使用

    public static void main(String[] args) {
     
         StringBuilder sb1 = new StringBuilder(16);
         sb1.append("Amos");
         sb1.append("Wong");
         System.out.println(sb1);
         //也可以链式编程
         sb1.append(" is").append(" no.1");
         System.out.println(sb1);
    }

    3.删除字符串中指定位置的字符

    1     public static void main(String[] args) {
    2  
    3      StringBuilder sb1 = new StringBuilder(16);
    4      sb1.append("Amos");
    5      sb1.append("Wong");
    6      sb1.delete(0, 1);
    7      System.out.println(sb1);
    8     }
  • 相关阅读:
    python ORM的使用
    python写入mysql
    远程连接不上centos的mysql的解决方法
    linux上mysql的安装
    缓存模块redis
    topic模式下的收发
    direct模式下的收发
    广播模式下的生产者与消费者fanout模式
    [HNOI2008]玩具装箱TOY
    [NOI2009]二叉查找树
  • 原文地址:https://www.cnblogs.com/AmosWong/p/9497314.html
Copyright © 2020-2023  润新知