zoukankan      html  css  js  c++  java
  • JAVA——String类indexOf()和substring()用法详解

    indexOf()的四种用法

    indexOf(int ch)
    返回指定字符在此字符串中第一次出现处的索引,未找到返回-1。
    例如

    String str1="01234543210";
    char ch='2';
    System.out.println( str1.indexOf(ch) );
    

    输出结果:2
    indexOf(int ch, int fromIndex)
    从指定的索引开始搜索,返回指定字符在此字符串中第一次出现处的索引,未找到返回-1。
    例如

    String str1="01234543210";
    char ch='2';
    System.out.println( str1.indexOf(ch,4));
    

    输出结果:8
    indexOf(String str)
    返回指定字符串在此字符串中第一次出现处的索引,未找到返回-1。
    例如

    String str1="012345012345";
    String str2="123";
    System.out.println( str1.indexOf(str2));
    

    输出结果:1
    indexOf(String str, int fromIndex)
    从指定的索引开始搜索,返回指定字符串在此字符串中第一次出现处的索引,未找到返回-1。
    例如

    String str1="012345012345";
    String str2="123";
    System.out.println( str1.indexOf(str2,2));
    

    输出结果:7

    substring()的两种用法

    substring(int beginIndex)
    返回该字符串的子字符串,子字符串从指定索引处的字符开始,直到该字符串的末尾结束。
    例如

    String str1="happyday";
    System.out.println(str1.substring(2));
    

    输出结果:"ppyday"
    substring(int beginIndex, int endIndex)
    返回该字符串的子字符串,子字符串从指定的索引beginIndex处开始,直到索引endIndex - 1处结束。因此子字符串的长度是endIndex-beginIndex。
    例如

    String str1="happyday";
    System.out.println(str1.substring(2,6));
    

    输出结果:"ppyd"

  • 相关阅读:
    取消chrome(谷歌浏览器)浏览器下最小字体限制
    函数声明方式及作为值的函数
    常用的正则表达式
    8腾讯云服务器账号密码
    errno -4058 and npm WARN enoent ENOENT 解决方案
    node gyp的问题
    npm 版本问题
    无缘无故出现npm 解析异常的的问题 解决方案
    idea注册码
    以太坊测试网络 账号密码
  • 原文地址:https://www.cnblogs.com/weiyining/p/13181016.html
Copyright © 2011-2022 走看看