Java方法:indexOf(),charAt(),subString()整理

1.indexOf():

str.IndexOf(Char) 方法:报告指定 Unicode 字符或字符串在此实例中的第一个匹配项的从零开始的索引。

 如果未在此实例中找到该字符或字符串,则此方法返回 -1。

String.IndexOf(Char, Int32):报告指定 Unicode 字符在此字符串中的第一个匹配项的从零开始的索引。 该搜索从指定字符位置开始。

例:String str = "我123是谁,你又是谁?,abcdefg,ABCDEFG";

      System.out.println(str.indexOf("是"));// 默认是从0开始查找     ---4
      System.out.println(str.indexOf("是", 5));// 从5后开始查找"是",所以这里对应的为"你又是谁"中的"是"    ----9
      System.out.println(str.indexOf(65));// 65对应Unicode中的A          ----21
      System.out.println(str.indexOf(97, 7));// 97对应Unicode中的a,表示从第7后开始查找a         ----13

2.charAt():前后端都可用

str.charAt(int index) :返回指定索引处的字符。索引范围为从 0 到 length() - 1。

例:str.charAt(0)                     检索str中的第一个字符

      str.charAt(str.length()-1)   检索str中的最后一个字符

      var str = "HELLO WORLD";
      var n = str.charAt(2)          -------n结果为L

3.subString():索引位置从0开始

str.substring(int beginIndex);截取str中从beginIndex开始至末尾的字符串;

补充: 若beginIndex大于str的长度,那么 java.lang.StringIndexOutOfBoundsException: String index out of range: -X

str.substring(int beginIndex,int endIndex);截取str中从beginIndex开始至endIndex结束时的字符串;

补充:  beginIndex =< 截取str的值 < endIndex(左闭右开)

IndexOutOfBoundsException - 如果 beginIndex 为负,或 endIndex 大于此 String 对象的长度,或 beginIndex 大于 endIndex

例:"helloworld".substring(5)      ----"world"

    "helloworld".substring(10)      ----""

    "helloworld".substring(11)      ---- java.lang.StringIndexOutOfBoundsException: String index out of range: -1

    "hamburger".substring(4, 8)   ---- "urge"
    "smiles".substring(1, 5)          ---- "mile"

原文地址:https://www.cnblogs.com/whhjava/p/6890579.html