JAVA实现输入2个字符串S1和S2,要求删除字符串S1中出现的所有子串S2,即结果字符串中不能包含S2。
时间: 2023-12-30 15:47:45 浏览: 95
可以使用Java中的字符串操作方法来实现删除子串S2。
具体实现步骤如下:
1. 使用Java字符串的replace()方法将S1中所有的S2替换为空字符串,得到新的字符串S3。
2. 返回新的字符串S3作为结果。
以下是实现代码:
```java
public class RemoveSubstring {
public static void main(String[] args) {
String s1 = "hello world, hello java";
String s2 = "hello";
String s3 = removeSubstring(s1, s2);
System.out.println(s3);
}
public static String removeSubstring(String s1, String s2) {
return s1.replaceAll(s2, "");
}
}
```
在上面的代码中,使用了Java中的replaceAll()方法来替换S1中所有的S2子串,得到新的字符串S3。最后将S3作为结果返回。
相关问题
JAVA实现输入2个字符串S1和S2,要求删除字符串S1中出现的所有子串S2,即结果字符串中不能包含S2。输入2行以回车结束的非空字符串,对应S1和S2。在一行中输出删除字符串S1中出现的所有子串S2后的结果字符串。
以下是实现代码:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s1 = scanner.nextLine();
String s2 = scanner.nextLine();
String result = s1.replaceAll(s2, "");
System.out.println(result);
}
}
```
首先用 `Scanner` 类获取用户输入的两个字符串 `s1` 和 `s2`,然后调用 `replaceAll()` 方法将 `s1` 中所有的 `s2` 子串替换为空字符串,得到结果字符串 `result`,最后输出 `result` 即可。
输入2个字符串S1和S2,要求删除字符串S1中出现的所有子串S2,即结果字符串中不能包含S2。
可以使用字符串替换的方法来实现删除字符串S1中所有出现的子串S2。具体步骤如下:
1. 使用字符串的 replace() 方法,将S1中所有的S2替换为空字符串 ""。
2. 返回替换后的S1字符串。
以下是 Python 代码实现:
```python
def delete_substring(s1, s2):
return s1.replace(s2, "")
```
示例:
```python
s1 = "hello world, world is beautiful"
s2 = "world"
result = delete_substring(s1, s2)
print(result) # 输出:hello , is beautiful
```
注意:该方法只能删除S1中出现的所有S2子串,无法处理S1中某些子串被S2包含的情况。例如,若S1="hello worl",S2="world",则该方法无法处理。
阅读全文
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.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)