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"

  • 相关阅读:
    hexo博客搭建
    HDFS基本命令
    hadoop简单排序
    HBase实验
    linux版python升级依赖项问题
    hadoop大数据生态安装
    linux-anoconda更换镜像
    [渣译文] 使用 MVC 5 的 EF6 Code First 入门 系列:排序、筛选和分页
    [渣译文] 使用 MVC 5 的 EF6 Code First 入门 系列:实现基本的CRUD功能
    [渣译文] 使用 MVC 5 的 EF6 Code First 入门 系列:建立一个EF数据模型
  • 原文地址:https://www.cnblogs.com/weiyining/p/13181016.html
Copyright © 2011-2022 走看看