Java 检查 2 个字符串是否包含相同的字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3985328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Checking if 2 strings contain the same characters?
提问by Brent
Is there a way to check if two strings contain the same characters. For example,
有没有办法检查两个字符串是否包含相同的字符。例如,
abc, bca -> true
aaa, aaa -> true
aab, bba -> false
abc, def -> false
回答by GaryF
Turn each string into a char[], sort that array, then compare the two.
将每个字符串转换为 char[],对该数组进行排序,然后比较两者。
private boolean sameChars(String firstStr, String secondStr) {
char[] first = firstStr.toCharArray();
char[] second = secondStr.toCharArray();
Arrays.sort(first);
Arrays.sort(second);
return Arrays.equals(first, second);
}
回答by codaddict
You can convert the string into char array, sort the arrays and them compare the arrays:
您可以将字符串转换为字符数组,对数组进行排序并比较数组:
String str1 = "abc";
String str2 = "acb";
char[] chars1 = str1.toCharArray();
char[] chars2 = str2.toCharArray();
Arrays.sort(chars1);
Arrays.sort(chars2);
if(Arrays.equals(chars1,chars2)) {
System.out.println(str1 + " and " + str2 + " are anagrams");
} else {
System.out.println(str1 + " and " + str2 + " are not anagrams");
}
回答by Erhan Bagdemir
here:
这里:
String str1 = "abc";
String str2 = "cba";
/* create sorted strings */
/* old buggy code
String sorted_str1 = new String( java.utils.Arrays.sort(str1.toCharArray()) );
String sorted_str2 = new String( java.utils.Arrays.sort(str2.toCharArray()) );
*/
/* the new one */
char [] arr1 = str1.toCharArray();
char [] arr2 = str2.toCharArray();
java.utils.Arrays.sort(arr1);
java.utils.Arrays.sort(arr2);
String sorted_str1 = new String(arr1);
String sorted_str2 = new String(arr2);
if (sorted_str1.equals( sorted_str2 ) ) {
/* true */
} else {
/* false */
}
回答by Jean
A very easy - but not very efficient - way to do that is, convert your String
s to char arrays and use java.util.Arrays.sort on them, get String
s back and compare for equality.
If your strings are under a few thousand characters, that should be very okay.
一种非常简单但不是很有效的方法是,将您的String
s转换为 char 数组并在它们上使用 java.util.Arrays.sort,取回String
s 并比较相等性。如果您的字符串少于几千个字符,那应该没问题。
If you have several megabytes strings, you may want to create an array with a count for each character (using its code as an index), have one pass on one string adding one on the count of each char, and one pass on the second string removing one. If you fall under 0 at any point during the second pass, they don't have the same characters. When you're done with the second string without error, you are sure they have the same characters if they have the same length (which you should have checked first anyway).
This second method is much more complicated than sorting the strings, and it requires a big array if you want to work with unicode strings, but it's perfectly good if you're okay with only the 128 chars of the ascii set, and much faster.
Do NOT bother with that if you don't have several million characters in your strings. Sorting the strings is much easier, and not significantly slower on strings with only a couple dozen chars.
如果你有几兆字节的字符串,你可能想创建一个数组,每个字符都有一个计数(使用它的代码作为索引),对一个字符串进行一次传递,在每个字符的计数上加一,并在第二个传递一次字符串删除一个。如果您在第二遍的任何时候都低于 0,则它们的字符不相同。当您完成第二个字符串且没有错误时,如果它们的长度相同,您可以确定它们具有相同的字符(无论如何您应该先检查一下)。
第二种方法比对字符串进行排序要复杂得多,如果您想使用 unicode 字符串,它需要一个大数组,但如果您只对 128 个 ascii 字符集没问题,它就非常好,而且速度要快得多。
如果您的字符串中没有几百万个字符,请不要担心。对字符串进行排序要容易得多,并且在只有几十个字符的字符串上并没有明显变慢。
回答by sleske
As a (nitpicking ;-) ) side note:
作为(吹毛求疵 ;-) )旁注:
Be aware that the solutions proposed here only work for strings composed of characters from the Basic Multilingual Plane(BMP) of Unicode.
请注意,此处提出的解决方案仅适用于由Unicode的基本多语言平面(BMP) 中的字符组成的字符串。
Characters outside the BMP are represented as a pairof char
in a String
, so you need to pay extra attention, so you keep the pairs together. See the Javadocs of java.lang.Character
for the gory details.
在BMP之外的字符被表示为一双的char
一个String
,所以你需要格外注意,所以你保持对在一起。有关java.lang.Character
详细信息,请参阅 的 Javadoc 。
Fortunately, most characters outside the BMP are rather exotic. Even most of Japanese and Chinese is in the BMP...
幸运的是,BMP 之外的大多数角色都颇具异国情调。甚至大部分日本人和中国人都在BMP中......
回答by Jayan
Consider creating a signature for a given String. Using count and character.
考虑为给定的字符串创建签名。使用计数和字符。
a-count:b-count:c-count:.....:z-count:
(extend for upper case if you want ).
a-count:b-count:c-count:.....:z-count:
(如果需要,可以扩展为大写)。
Then compare the signature. This should scale better for very large Strings.
然后比较签名。对于非常大的字符串,这应该可以更好地扩展。
As a shortcut, check the length. If they are not matching, return false anyway.
作为一种快捷方式,检查长度。如果它们不匹配,无论如何都返回 false。
回答by u443966
Maybe it's not the fastest answer, but it must be shortest answer.
也许这不是最快的答案,但一定是最短的答案。
boolean hasSameChar(String str1, String str2){
for(char c : str1.toCharArray()){
if(str2.indexOf(c) < 0 ) return false;
}
for(char c : str2.toCharArray()){
if(str1.indexOf(c) < 0 ) return false;
}
return true;
}
回答by Siba
Here:
这里:
import java.util.Arrays;
public class CompareString {
公共类比较字符串{
String str = "Result";
String str1 = "Struel";
public void compare() {
char[] firstString = str.toLowerCase().toCharArray();
char[] secondString = str1.toLowerCase().toCharArray();
Arrays.sort(firstString);
Arrays.sort(secondString);
if (Arrays.equals(firstString, secondString) == true) {
System.out.println("Both the string contain same charecter");
} else {
System.out.println("Both the string contains different charecter");
}
}
public static void main(String[] args) {
CompareString compareString = new CompareString();
compareString.compare();
}
}
}