【问题标题】:Difference between String.indexOf(int x) and String.indexOf(String) [closed]String.indexOf(int x) 和 String.indexOf(String) 之间的区别 [关闭]
【发布时间】:2013-08-11 00:10:26
【问题描述】:

String 类中有两个方法看起来做同样的事情:

  • indexOf(int)
  • indexOf(String)

谁能解释一下这两个函数有什么区别?

【问题讨论】:

  • 阅读 javadoc。该社区不欢迎此类问题,即您可以通过谷歌搜索轻松阅读这些方法。阅读有关重载的内容。
  • 公平地说,在大多数人期望 char 的地方使用 int 可能会有点令人困惑
  • @BradMace - 但我确信 javadoc 也解释了这一点。关键是 Java 程序员应该总是首先检查 javadoc 中是否存在这样的问题。

标签: java string


【解决方案1】:
    String str = "abcdefabc";            
    System.out.println(str.indexOf(97)); //97 is int value of 'a'.
     //so this will return first occurrence of 'a'
    System.out.println(str.indexOf("b")); // this will return first 
    //occurrence of "b" in the String

【讨论】:

    【解决方案2】:

    String.indexOf(int ch)

    返回此字符串中第一个的索引 指定字符的出现。如果一个字符 值 ch 出现在字符序列中 由这个 String 对象表示,然后是索引(在 Unicode 代码单元)的第一个此类事件是 返回。

    String.indexOf(String str)

    如果字符串参数作为子字符串出现在 这个对象,然后是第一个字符的索引 首先返回这样的子字符串;如果它没有作为 子字符串,返回-1。

    【讨论】:

    • -1 表示重复答案。无需使用 API 的各种重新措辞使论坛变得混乱。
    【解决方案3】:
    • String.indexOf(int)Returns the index within this string of the first occurrence of the specified character
    • String.indexOf(String)Returns the index within this string of the first occurrence of the specified substring

    示例:

    String test = "aaabbbaaabbb";
    test.indexOf('a') return 0 (first 'a' in string)
    test.indexOf('b') return 3 (first 'a' in string)
    test.indexOf("aaa") return 0 (first "aaa" in string)
    test.indexOf("bbb") return 3 (first "bbb" in string)
    test.indexOf("sajx") return -1 (not found)
    

    【讨论】:

    • +1 展示了如何使用 String.indexof(int) 方法来定位特定字符的位置。
    【解决方案4】:
    indexOf(int ch) 
    

    返回此字符串中第一次出现指定字符的索引。

    这将帮助您识别字符串中存在的字符索引。

    indexOf(String str) 
    

    返回此字符串中指定子字符串第一次出现的索引。

    这将帮助您识别字符串中存在的子字符串的索引。

    【讨论】:

    • -1,OP可以自己读API(不知道怎么读API就不能编程)。如果 OP 对他们在 API 描述中不理解的内容有具体问题,那么他们应该就他们阅读的内容提出具体问题。
    • 这并不意味着用简单的语言解释的人那么文档中提到的内容应该得到反对票。反对票具体表示这个答案没有用,这里是不是这样????
    • 您基本上只是从 API 中复制了文本。我认为答案没有用,因为该信息可在 API 中找到。 OP 应该首先读取 API。
    • @camickr:如果您仔细阅读答案,您可以看到我解释的 API 的最后一行不是来自 API,并且我提到了我所知道的那个 API 的正确性。 bellabax,写的和 API 一样。这也是那个人可以通过谷歌获得的样本,所以他应该对此投反对票。
    猜你喜欢
    • 2014-10-10
    • 2016-02-12
    • 1970-01-01
    • 2014-10-29
    • 1970-01-01
    • 2011-08-20
    • 2013-01-26
    • 2011-07-05
    • 1970-01-01
    相关资源
    最近更新 更多