java,判断两个字符串是否含有相同的字母
时间: 2023-11-13 19:02:29 浏览: 74
可以使用数组来记录每个字母出现的次数,然后比较两个字符串的数组是否相同。具体实现可以参考以下代码:
```java
public static boolean hasSameLetters(String s1, String s2) {
int[] count1 = new int[26];
int[] count2 = new int[26];
for (char c : s1.toCharArray()) {
count1[c - 'a']++;
}
for (char c : s2.toCharArray()) {
count2[c - 'a']++;
}
for (int i = 0; i < 26; i++) {
if (count1[i] != count2[i]) {
return false;
}
}
return true;
}
```
在这个方法中,我们首先使用两个数组 `count1` 和 `count2` 分别记录两个字符串中每个字母出现的次数。然后,我们比较两个数组是否相同,如果不同则说明两个字符串中含有不同的字母,返回 `false`;否则说明两个字符串中含有相同的字母,返回 `true`。
相关问题
java中判断两个字符串是否相同
在Java中可以使用equals()方法来判断两个字符串是否相同。例如:
```
String str1 = "hello";
String str2 = "hello";
if(str1.equals(str2)){
System.out.println("两个字符串相同");
} else {
System.out.println("两个字符串不相同");
}
```
注意:在Java中,判断两个字符串是否相同不能使用==运算符,因为它比较的是两个字符串对象的引用,而不是它们的内容。
java判断两个字符串是否相等
在Java中,要判断两个字符串是否相等,可以使用以下几种方法:
1. 使用equals()方法:使用字符串的equals()方法来比较两个字符串是否相等。示例代码如下:
```java
String str1 = "Hello";
String str2 = "World";
boolean isEqual = str1.equals(str2);
System.out.println(isEqual); // 输出false
```
2. 使用equalsIgnoreCase()方法:如果要忽略字符串的大小写,可以使用equalsIgnoreCase()方法来比较。示例代码如下:
```java
String str1 = "Hello";
String str2 = "hello";
boolean isEqual = str1.equalsIgnoreCase(str2);
System.out.println(isEqual); // 输出true
```
3. 使用==运算符:在Java中,使用==运算符可以比较两个字符串的引用是否相等。示例代码如下:
```java
String str1 = "Hello";
String str2 = "Hello";
boolean isEqual = (str1 == str2);
System.out.println(isEqual); // 输出true
```
需要注意的是,使用==运算符比较的是两个字符串对象的引用是否相等,而不是比较字符串的内容是否相等。
希望以上信息对您有所帮助!如果还有其他问题,请随时提问。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)