API-String类介绍

String 类

  1. 字符串都是对象。
  2. 一旦初始化就不能被更改。因为是常量。
  3. 通过String类的构造函数可以知道,将字节数组或者字符转成字符串。
public class StringDemo {

    public static void main(String[] args) {

        String str="abcd";
        System.out.println("str ="+str);

        //--------------------
        System.out.println("-----多个引用指向同一个字符串------");
        String s1="itcast";
        String s2="itcast";
        System.out.println(s1==s2);
        System.out.println("-----两个内容相同,创建方式不同的字符串,面试题------");
        String s3="abc";
        String s4=new String("abc");
        /*s3和s4有什么不同呢?
         * s3创建,在内存中有一个对象。
         * 
         * s4创建,在内存中有两个对象。
         * "abc"是一个对象,然后又new了一个对象,即
         * */
        System.out.println(s3==s4);//false
        System.out.println(s3.equals(s4));//true
//      true 因为String复写了equals的方法
//      建立字符串自己的判断依据,通过字符串中的内容来判断。      

    }

}
public class StringDemo2 {

    public static void main(String[] args) {
        /*
         * 1,字符串是一个对象,那么它的方法必然是围绕操作这个对象的数据定义的。
         * 2,你认为字符串中有哪些功能呢?
         *  2.1有多少个字符?
         *      int length()
         * 
         *  2.2字符的位置
         *      int indexOf(ch,fromIndex);
         * 
         *  2.3获取指定位置上的字符。
         *      char charAt(int)
         * 
         *  2.4获取部分字符串。
         *      String substring(int beginIndex, int endIndex)
         * */
        String str="abade";
        System.out.println("length="+str.length());
        System.out.println("index1="+str.indexOf('a'));
        System.out.println("index2="+str.indexOf('a', 0));
        System.out.println("index3="+str.indexOf('a', 1));

        str="dsadusahdashfuhashfal";
        System.out.println("index4="+str.lastIndexOf('l'));

        str="itcast";
        System.out.println("ch="+str.charAt(3));
        System.out.println("newstr="+str.substring(2, 4));
        //注意substring方法的结束索引是endIndex-1的位置
        //关键是:根据自己所需的功能,学会查阅API。

    }

}
public class StringTest {
    public static void main(String[] args) {
        /*
         * String方法查找练习。
           1,字符串是否指定字符串开头,结尾同理。
           boolean startsWith(String prefix) 
           boolean endsWith(String suffix)

           2,字符串中是否包含另一个字符串出现的位置。
           boolean contains(CharSequence s) 
           int indexOf(String str) //返回为-1则为不存在

           3.字符串中另一个字符串出现的位置。
           int indexOf(String str) 

           4,将字符串中指定的字符串替换成另一个字符串。
           String replace(CharSequence target, CharSequence replacement)
           5,字符串如何比较大小?

           6,将字符串转换成一个字符数组,或者字节数组。
           char[] toCharArray() 
           byte[] getBytes()
           7,将字符串转换成大写的字母字符串。
           String toUpperCase()
           String toLowerCase()
           8,将自字符串按照指定的方式分解成多个字符串,“lisi,wangwu,zhaoliu”获取三个姓名。
            String[] split(String regex)    
        */
        //1
        String str="StringDemo.java";
        boolean b1=str.startsWith("Demo");//false
        System.out.println(b1);
        //2
        boolean b2=str.contains("Demo");//CharSequence x="Demo";
        System.out.println(b2);
        //4
        String s=str.replace("Demo", "Test");
        System.out.println(s);
        //6
        char[] chs=str.toCharArray();
        byte[] bytes=str.getBytes();
        //7
        String upperString=str.toUpperCase();
        System.out.println(upperString);
        String lowerString=str.toLowerCase();
        System.out.println(lowerString);
        //8
        str="lisi,wangwu,zhaoliu";
        String[] names=str.split(",");
        for (int i = 0; i < names.length; i++) {
            System.out.println(names[i]);
        }
        //5 字符串如何比较大小?
        int result="ab".compareTo("ac");
        //只要想对象具备比较大小的功能只需要实现Compareble接口
        System.out.println(result);

    }

}

学会查阅API,了解String的几个功能。

public class Person implements Comparable{
        private String name;
        private int age;

        public Person() {
            super();
        }
        public Person(String name, int age) {
            super();
            this.name = name;
            this.age = age;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
        /*
         * 建立了Person判断对象是否是否相同的依据。
         * 只要是同姓名同年龄就是同一个人。
         * @see java.lang.Object#equals(java.lang.Object)
         */

        @Override
        public boolean equals(Object obj) {
            if(this==obj)
                return true ;
            if(!(obj instanceof Person )){
                throw new ClassCastException("类型错误");
            }
            Person p=(Person)obj;
            return this.name.equals(p.name)&&this.age==p.age;
        }

        @Override
        public String toString() {
            return "Person [name=" + name + ", age=" + age + "]";
        }
        /**
         * 比较年龄的方法
         */
        @Override
        public int compareTo(Object o) {
            if(!(o instanceof Person )){
                throw new ClassCastException("类型错误");
            }
            Person p=(Person)o;
    /*      if(this.age>p.age)
                return 1;
            if(this.age<p.age)
                return -1;*/
            return this.age-p.age;
        }
        //熟练掌握alt+shift+s 快捷键的使用
        //可以快速地得到构造器,get和set方法。

    }
    熟练掌握alt+shift+s 快捷键的使用
    可以快速地得到构造器,get和set方法。

案例一

字符串数组
[“abc”,”nba”,”cctv”,”itcast”]
从小到大排序

public class StringTest2 {

    public static void main(String[] args) {
    /*
     * 案例一:字符串数组
     * ["abc","nba","cctv","itcast"]
     * 从小到大排序
     */
    String[] strs={"abc","nba","cctv","itcast"};
    printArray(strs);
    sortString(strs);
    printArray(strs);
    }

    /*
     * 字符串数组排序
     * 思路:
     * for嵌套循环
     * 循环中进行元素的大小比较,满足条件位置置换。
     */
    public static void sortString(String[] strs) {
        for (int i = 0; i < strs.length-1; i++) {
            for (int j = i+1; j < strs.length; j++) {
                if(strs[i].compareTo(strs[j])>0){
                    swap(strs,i,j);
                }   
            }       
        }
//      Arrays.sort(strs);
    }
    /*
     * 数组元素位置交换
     */
    private static void swap(String[] strs, int i, int j) {
        String temp=strs[i];
        strs[i]=strs[j];
        strs[j]=temp;

    }
    /*
     * 打印字符串数组
     */
    private static void printArray(String[] strs) {
        for (int i = 0; i < strs.length; i++) {
            System.out.print(strs[i]+" ");
        }
        System.out.println();
    }

}

案例二

问:
“daitcastdafaitcastdafaitcastdsaddwaditcast”有几个itcast

public class StringTest2_2 {

    public static void main(String[] args) {
        /* 
         * 案例二:
         * "daitcastdafaitcastdafefaefaitcastdsaddwaditcast"有几个itcast
         *
         *思路:
         *1,在一个字符串中查找另一个字符串,indexOf。
         *2,查找到第一次出现的指定字符串后,如何查找第二个呢?
         * 
         */
        String str="daitcastdafaitcastdafefaefaitcastdsaddwaditcast";
        String key="itcast";
        int count =getkeyCount(str,key);
        System.out.println("count="+count);
    /*  int x=str.indexOf(key);
        System.out.println("x="+x);

        int y=str.indexOf(key,x+key.length());
        System.out.println("y="+y);
        代码复用性差,定义方法用循环解决。
        */

    }

    public static int getkeyCount(String str, String key) {
        //1,定义变量,记录每一次找到key的位置。
        int index =0;
        //2,定义变量,记录出现的次数
        int count=0;
        //3,定义循环,只要查到的结果不是-1,继续查找
        while((index=str.indexOf(key, index))!=-1){
            System.out.println("index="+index);

            index=index+key.length();

            count++;
        }
        return count;
    }

}

案例三

     * "itcast_sh"要求,将该字符串按照长度由长到短打印出来。
     * itcast_sh
     * itcast_s
     * tcast_sh
public class StringTest2_3 {

    public static void main(String[] args) {
        /*
         * 
         * 案例三:
         * "itcast_sh"要求,将该字符串按照长度由长到短打印出来。
         * itcast_sh
         * itcast_s
         * tcast_sh
         */
        String str="itcast_sh";
        printStringByLength(str);
    }

    public static void printStringByLength(String str) {
        // 1,通过分析,发现是for嵌套循环
        for (int i = 0; i < str.length(); i++) {
            for (int start = 0,end=str.length()-i; end <=str.length(); start++,end++)
            {
                String temp=str.substring(start, end);
                System.out.println(temp);

            }
        }

    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值