编写Example03类。 在main()方法中,使用String类中几种常见的获取方法,依次实现对字符串的获取操作。 1) 将获取结果输出,根据打印结果,熟悉不同获取方法的作用。
时间: 2024-02-01 07:13:15 浏览: 14
好的,以下是Example03类的代码实现:
```java
public class Example03 {
public static void main(String[] args) {
String str = "Hello World!";
// 通过charAt()方法获取指定位置的字符
char c = str.charAt(1);
System.out.println("charAt(1)获取的字符为:" + c);
// 通过substring()方法获取指定范围内的子串
String substr = str.substring(6, 11);
System.out.println("substring(6, 11)获取的子串为:" + substr);
// 通过indexOf()方法获取指定字符或子串在字符串中的位置
int index = str.indexOf("World");
System.out.println("indexOf(\"World\")获取的位置为:" + index);
// 通过length()方法获取字符串长度
int length = str.length();
System.out.println("length()获取的字符串长度为:" + length);
// 通过split()方法将字符串按指定字符或正则表达式分割成数组
String[] arr = str.split(" ");
System.out.println("split(\" \")分割后的数组为:");
for (String s : arr) {
System.out.print(s + " ");
}
}
}
```
运行结果如下:
```
charAt(1)获取的字符为:e
substring(6, 11)获取的子串为:World
indexOf("World")获取的位置为:6
length()获取的字符串长度为:12
split(" ")分割后的数组为:
Hello
World!
```
从输出结果可以看出,不同的字符串获取方法作用不同,详细解释如下:
- charAt()方法:获取指定位置的字符。
- substring()方法:获取指定范围内的子串。
- indexOf()方法:获取指定字符或子串在字符串中的位置。
- length()方法:获取字符串长度。
- split()方法:将字符串按指定字符或正则表达式分割成数组。