用Java语言找出两个字符串中所有共同的字符。
时间: 2024-03-06 21:48:31 浏览: 30
可以使用两个嵌套的循环来遍历两个字符串的所有字符,然后比较是否相同。如果相同,则将该字符添加到一个新的字符串中,最后返回新的字符串即可。
以下是Java代码实现:
```java
public static String findCommonChars(String str1, String str2) {
String result = "";
for (int i = 0; i < str1.length(); i++) {
char c1 = str1.charAt(i);
for (int j = 0; j < str2.length(); j++) {
char c2 = str2.charAt(j);
if (c1 == c2 && result.indexOf(c1) == -1) {
result += c1;
break;
}
}
}
return result;
}
```
你觉得这个回答满意吗?
相关推荐
![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)
![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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)