扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

java中indexof方法怎么使用

扬州沐宇科技
2024-03-14 16:55:24
Java

在Java中,indexOf()方法用于查找指定元素在字符串中第一次出现的位置。方法的语法如下:

public int indexOf(String str)

参数str是要查找的字符串,方法返回值是指定字符串在原字符串中第一次出现的位置(索引),如果未找到,则返回-1。

下面是一个示例代码:

String str = "Hello, World!";
int index = str.indexOf("World");
System.out.println("The index of 'World' in the string is: " + index);

在这个例子中,indexOf()方法将在字符串"Hello, World!"中查找子字符串"World"的位置,并将结果打印出来。

扫码添加客服微信