1) 编写Example03类。 2) 在main()方法中,使用String类中的替换和切割等方法,对字符串的操作。 3) 将操作结果输出,根据打印结果,熟悉上述替换和切割方法的作用。
时间: 2024-02-01 14:13:45 浏览: 28
以下是Example03类的代码,其中使用了String类中的replace()、replaceAll()、split()方法对字符串进行操作:
```
public class Example03 {
public static void main(String[] args) {
String str = "Hello, world! This is an example string.";
// 使用replace()方法替换字符串中的字符
String newStr = str.replace('o', '0');
System.out.println("使用replace()方法替换字符:");
System.out.println("原始字符串:" + str);
System.out.println("替换后字符串:" + newStr);
// 使用replaceAll()方法替换字符串中的子串
String newStr2 = str.replaceAll("example", "sample");
System.out.println("使用replaceAll()方法替换子串:");
System.out.println("原始字符串:" + str);
System.out.println("替换后字符串:" + newStr2);
// 使用split()方法切割字符串
String[] strArr = str.split(" ");
System.out.println("使用split()方法切割字符串:");
System.out.println("原始字符串:" + str);
System.out.print("切割后字符串:");
for (String s : strArr) {
System.out.print(s + "/");
}
}
}
```
运行结果如下:
```
使用replace()方法替换字符:
原始字符串:Hello, world! This is an example string.
替换后字符串:Hell0, w0rld! This is an example string.
使用replaceAll()方法替换子串:
原始字符串:Hello, world! This is an example string.
替换后字符串:Hello, world! This is an sample string.
使用split()方法切割字符串:
原始字符串:Hello, world! This is an example string.
切割后字符串:Hello, /world!/,This/ is/ an/ example/ string./
```
可以看到,使用replace()方法可以将字符串中的某个字符替换为另一个字符;使用replaceAll()方法可以将字符串中的某个子串替换为另一个子串;使用split()方法可以将字符串按照某个分隔符进行切割,返回一个字符串数组。