×

Groovy 教程

Groovy 概述Groovy 环境Groovy 基本语法Groovy 数据类型Groovy 变量Groovy 运算符Groovy 循环Groovy 条件语句Groovy 方法Groovy 文件I/OGroovy 可选Groovy 数字Groovy 字符串Groovy 范围Groovy 列表Groovy 映射Groovy 日期和时间Groovy 正则表达式Groovy 异常处理Groovy 面向对象Groovy 泛型Groovy 特征Groovy 闭包Groovy 注释Groovy XMLGroovy JMXGroovy JSONGroovy DSLSGroovy 数据库Groovy 构建器Groovy 命令行Groovy 单元测试Groovy 模板引擎Groovy 元对象编程

Groovy indexOf()方法


Groovy 字符串Groovy 字符串


返回此字符串中指定子字符串第一次出现的索引。此方法有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 - 从哪里开始搜索

返回值

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

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

参数

int indexOf(String str)

参数

Str - 要搜索的字符串

返回值

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

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

参数

int indexOf(String str, int fromIndex)

参数

str - 要搜索的字符串

  • fromIndex – where to start the search from

返回值 - 返回指定子字符串第一次出现的此字符串中的索引,从指定的索引开始。 如果不发生,则返回-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 字符串Groovy 字符串


分类导航

关注微信下载离线手册

bootwiki移动版 bootwiki
(群号:472910771)