當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java Java.lang.String.indexOf()用法及代碼示例


描述

這個java.lang.String.indexOf(int ch) 方法返回此字符串中第一次出現指定字符的索引。

如果一個帶有值的字符ch出現在此 String 對象表示的字符序列中,然後返回第一次出現的索引(Unicode 代碼單元)。

聲明

以下是聲明java.lang.String.indexOf()方法

public int indexOf(int ch)

參數

ch─ 這是一個字符(Unicode 代碼點)。

返回值

此方法返回此對象表示的字符序列中該字符第一次出現的索引,如果該字符沒有出現,則返回 -1。

異常

NA

示例

下麵的例子展示了 java.lang.String.indexOf() 方法的用法。

package com.tutorialspoint;

import java.lang.*;

public class StringDemo {

   public static void main(String[] args) {

      String str = "This is tutorialspoint";
       
      // returns the index of occurrence of character s
      System.out.println("index of letter 's' = " 
         + str.indexOf('s')); 
      
      // returns -1 as character e is not in the string
      System.out.println("index of letter 'e' = " 
         + str.indexOf('e'));
   }
}

讓我們編譯並運行上麵的程序,這將產生以下結果——

index of letter 's' = 3
index of letter 'e' = -1

相關用法


注:本文由純淨天空篩選整理自 Java.lang.String.indexOf() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。