常用类--String类--String类的获取功能

String类的获取功能

程序示例

/*
        String类的获取功能
                int length()
                char charAt(int index)
                int indexOf(int ch)
                int indexOf(String str)
                int indexOf(int ch,int fromIndex)
                int indexOf(String str,int fromIndex)
                String substring(int start)
                String substring(int start,int end)
*/
public class StringDemo7 {
    public static void main(String[] args) {
        String s = "helloworld";

        //int length() 获取字符串的长度
        System.out.println(s.length());//10
      
        System.out.println("*************************");

        //char charAt(int index) 返回char字符指定索引位置的值
            //输入索引,返回对应位置的值
        //索引从0开始到length()-1
        System.out.println(s.charAt(7));//r
        System.out.println(s.charAt(0));//h
      //StringIndexOutOfBoundsException--字符串索引越界异常
//        System.out.println(s.charAt(100));

        System.out.println("*************************");
      
        //int indexOf(int ch)
        //返回指定字符第一次出现的字符串内的索引
        //如果此字符串中没有此类字符,则返回-1 。
        System.out.println(s.indexOf('l'));//2
         //底层会将97通过ASCII码表转换为对应的字符a
        System.out.println(s.indexOf(97));//-1
      
        System.out.println("*************************");
      
        //int indexOf(String str)
        //返回的是小字符串第一个字符在大字符串中的索引值
        //如果此大字符串中没有此类小字符串,则返回-1 。
        System.out.println(s.indexOf("owo"));//4
        System.out.println(s.indexOf("qwer"));//-1
      
        System.out.println("*************************");
      
        //int indexOf(int ch,int fromIndex)
        //返回指定字符第一次出现在字符串中的索引,以指定的索引开始搜索
           //我想搜索字符'l',从索引4开始搜索
        System.out.println(s.indexOf('l',4));//8(返回的是索引下标)
        //若是搜索的字符在字符串中不存在,还是索引下标越界,返回的都是-1
        System.out.println(s.indexOf('p',4)); //-1
        System.out.println(s.indexOf('l',40));//-1
        System.out.println(s.indexOf('p',40));//-1

        System.out.println("*************************");
      
        //int indexOf(String str,int fromIndex)
            //与上一种情况类似只是把搜索字符改为搜索字符串
      
        System.out.println("*************************");
      
        //String substring(int start)
        //返回的是一个字符串,该字符串是此字符串的子字符串
        //子字符串从指定的索引处开始,并扩展到字符串的末尾
        //包含开始索引位置的值
        System.out.println(s.substring(3)); //loworld      
    //.StringIndexOutOfBoundsException--字符串索引越界异常
//        System.out.println(s.substring(20));

        System.out.println("*************************");
      
        //String substring(int start,int end)
        //返回的是一个字符串,该字符串是此字符串的子字符串
        //字串开始于start位置,并截取到end-1的位置
        //左闭右开  [,)  含头不含尾
        System.out.println(s.substring(5,10));//world
    //StringIndexOutOfBoundsException--字符串索引越界异常
//        System.out.println(s.substring(1,20));
    }
}
posted @ 2021-12-14 21:48  赤兔胭脂小吕布  阅读(42)  评论(0)    收藏  举报