- Groovy 教程
- Groovy - 首頁
- Groovy - 概述
- Groovy - 環境
- Groovy - 基本語法
- Groovy - 資料型別
- Groovy - 變數
- Groovy - 運算子
- Groovy - 迴圈
- Groovy - 決策
- Groovy - 方法
- Groovy - 檔案 I/O
- Groovy - 可選
- Groovy - 數字
- Groovy - 字串
- Groovy - 範圍
- Groovy - 列表
- Groovy - 對映
- Groovy - 日期和時間
- Groovy - 正則表示式
- Groovy - 異常處理
- Groovy - 面向物件
- Groovy - 泛型
- Groovy - 特質
- Groovy - 閉包
- Groovy - 註解
- Groovy - XML
- Groovy - JMX
- Groovy - JSON
- Groovy - DSL
- Groovy - 資料庫
- Groovy - 構建器
- Groovy - 命令列
- Groovy - 單元測試
- Groovy - 模板引擎
- Groovy - 元物件程式設計
- Groovy 有用資源
- Groovy - 快速指南
- Groovy - 有用資源
- Groovy - 討論
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 − 從哪裡開始搜尋
返回值
返回此字串中指定字元第一次出現的索引,從指定索引開始搜尋,如果字元不存在則返回 -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 – 從哪裡開始搜尋
返回值 − 返回此字串中指定子字串第一次出現的索引,從指定索引開始。如果它不存在,則返回 -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_strings.htm
廣告