使用int indexof(int ch,int fromIndex)写一串java代码
时间: 2023-12-23 22:02:36 浏览: 36
使用 `indexOf(int ch, int fromIndex)` 方法可以在字符串中查找指定字符的索引。以下是使用 `indexOf()` 方法编写的Java代码:
```java
public static void main(String[] args) {
String str = "Hello,World,Java";
int ch = 'o'; // 指定要查找的字符
int fromIndex = 0; // 指定开始查找的索引
int index = str.indexOf(ch, fromIndex);
if (index != -1) {
System.out.println("Index of '" + (char)ch + "' starting from index " + fromIndex + ": " + index);
} else {
System.out.println("Character '" + (char)ch + "' not found starting from index " + fromIndex);
}
}
```
这段代码将在字符串 "Hello,World,Java" 中查找字符 'o' 的索引。您可以通过更改变量 `ch` 和 `fromIndex` 的值来指定要查找的字符和开始查找的索引。如果找到了字符,则打印出其索引,否则打印出未找到字符的消息。请注意,`(char)` 是用于将整数转换为对应的字符。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)