Java代码:对于输入的每个字符串,查找其中的最大字母,在该字母后面插入字符串“(max)”及解释
时间: 2024-03-15 22:46:25 浏览: 69
以下是Java代码实现:
```
import java.util.Scanner;
public class InsertMaxString {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入字符串:");
String str = scanner.nextLine();
char maxChar = ' ';
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c > maxChar) {
maxChar = c;
}
}
int index = str.indexOf(maxChar);
String result = str.substring(0, index + 1) + "(max)" + str.substring(index + 1);
System.out.println("插入后的字符串为:" + result);
}
}
```
代码的实现思路是首先读入一个字符串,然后遍历字符串中的每个字符,找到其中的最大字母并记录下来。接着,通过`indexOf()`方法找到最大字母在字符串中的位置,然后使用`substring()`方法将字符串分为前后两部分,将`(max)`插入到最大字母后面,并将两部分字符串拼接在一起,最后输出插入后的字符串。
解释:
- `Scanner`是Java中的一个输入类,通过`nextLine()`方法可以读入一行字符串。
- `charAt()`方法可以获取字符串中指定位置的字符。
- `indexOf()`方法可以获取指定字符在字符串中的位置。
- `substring()`方法可以获取字符串中指定位置之间的子串。
阅读全文
相关推荐
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)