用 Java 在字符串中查找字符的索引


使用 indexOf() 方法来查找字符串中字符的索引。

假设我们的字符串如下。

String myStr = "amit";

现在,让我们在上面的字符串中查找字符 't' 的索引。

strIndex = myStr.indexOf('t');

以下是最终示例。

示例

 实时演示

public class Demo {
    public static void main(String[] args) {
       String myStr = "amit";
       int strIndex = 0;
       System.out.println("String: "+myStr);
       // finding index of character t
       strIndex = myStr.indexOf('t');
       System.out.println("Character m found at index: "+strIndex);
    }
}

输出

String: amit
Character m found at index: 3

更新时间:26-Jun-2020

1K+ 浏览

开启您的事业

完成课程以获得认证

开始使用
广告
© . All rights reserved.