int indexOf(String str,String c):获取c在字符串str对象中第一次出现的索引
时间: 2024-04-22 13:26:17 浏览: 22
如果你想要实现一个自定义的 `indexOf` 方法,它接收两个参数:一个字符串 `str` 和一个字符 `c`,并返回字符 `c` 在字符串 `str` 中第一次出现的索引,你可以使用以下代码实现:
```java
public class Main {
public static int indexOf(String str, String c) {
if (str == null || c == null || c.length() != 1) {
return -1;
}
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == c.charAt(0)) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
String str = "Hello World";
String c = "o";
int index = indexOf(str, c);
System.out.println("Index of \"" + c + "\" in str: " + index);
}
}
```
输出结果为:
```
Index of "o" in str: 4
```
在上面的示例中,我们定义了一个静态方法 `indexOf`,它接收一个字符串 `str` 和一个字符 `c`。在方法中,我们首先检查输入是否有效,然后使用一个循环遍历字符串 `str` 中的每个字符。如果找到与字符 `c` 相等的字符,我们就返回该字符的索引。如果没有找到匹配的字符,则返回 -1。
请注意,在这个自定义实现中,我们假设输入的字符串 `str` 和字符 `c` 都不为 null,并且字符 `c` 的长度为 1。如果输入不满足这些条件,方法会返回 -1。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)