当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


Groovy indexOf()用法及代码示例


返回此字符串中第一次出现指定子字符串的索引。此方法有 4 种不同的变体。

  • public int indexOf(int ch)- 返回此字符串中第一次出现指定字符的索引,如果该字符没有出现,则返回 -1。

用法

public int indexOf(int ch)

参数

ch - 要在字符串中搜索的字符。

返回值

返回此字符串中第一次出现指定字符的索引,如果该字符没有出现,则返回 -1。

  • public int indexOf(int ch, int fromIndex)- 返回此字符串中第一次出现指定字符的索引,从指定的索引处开始搜索,如果该字符没有出现,则返回 1。

用法

public int indexOf(int ch, int fromIndex)

参数

  • ch- 要在字符串中搜索的字符

  • fromIndex- 从哪里开始搜索

Return Value

返回此字符串中第一次出现指定字符的索引,从指定的索引处开始搜索,如果该字符没有出现,则返回 -1。

  • int indexOf(String str)- 返回此字符串中第一次出现指定子字符串的索引。如果它不是作为子字符串出现,则返回 -1。

用法

int indexOf(String str)

参数

Str - 要搜索的字符串

Return Value

返回此字符串中第一次出现指定子字符串的索引。如果它不是作为子字符串出现,则返回 -1。

  • int indexOf(String str, int fromIndex)- 返回此字符串中第一次出现指定子字符串的索引,从指定索引开始。如果没有发生,则返回 -1。

用法

int indexOf(String str, int fromIndex)

参数

str - 要搜索的字符串

  • fromIndex - 从哪里开始搜索

Return Value- 返回此字符串中第一次出现指定子字符串的索引,从指定索引开始。如果没有发生,则返回 -1。

以下是所有 4 种方法变体的用法示例

class Example { 
   static void main(String[] args) { 
      String a = "Hello World"; 
		
      // Using public int indexOf(int ch) 
      println(a.indexOf('e')); 
      println(a.indexOf('o')); 
		
      // Using public int indexOf(int ch, int fromIndex) 
      println(a.indexOf('l',1)); 
      println(a.indexOf('e',4));
		
      // Using public int indexOf(string str) 
      println(a.indexOf('el')); 
      println(a.indexOf('or')); 
		
      // Using public int indexOf(string str,int fromIndex) 
      println(a.indexOf('el',1)); 
      println(a.indexOf('or',8)); 
   } 
}

当我们运行上述程序时,我们将得到以下结果 -

1 
4 
2 
-1 
1 
7 
1 
-1

相关用法


注:本文由纯净天空筛选整理自 Groovy - indexOf()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。