我有两个包含数字的字符串,我想要判断第二个字符串是否包含与第一个字符串相同的数字,无论它们是否按顺序排列。如果有任何重复的数字,则报告为假。除了使用.charAt()之外,在Java中还有其他方法吗?因为对于10之后的数字不起作用。
String one = "1 2 3 4 5 ";
String two = " 3 2 1 4 5 ";
String three = "3 2 1 4 4 ";
Scanner.nextInt()
从字符串中读取数字,将它们添加到Set
中,然后查看set1.equals(set2)
是否为真。String one = "1 2 3 4 5 ";
String two = " 3 2 1 4 5 ";
Set<String> a = new HashSet<String> (Arrays.asList(one.trim().replaceAll("\\s*"," ").split(" ")));
Set<String> b = new HashSet<String> (Arrays.asList(two.trim().replaceAll("\\s*"," ").split(" ")));
boolean ret = (a.size() == b.size()) && a.containsAll(b);
String
转换为一个 List<Integer>
,使用 String.split()
和 Integer.parseInt()
对每个结果进行转换。然后,sort()
列表按升序排序,这样就很容易进行比较了。我首先会将数字解析为整数,将它们放入集合中并进行比较:
import java.util.SortedSet;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class StringsCompare {
private static String one = "1 2 3 4 5 6";
private static String two = " 3 2 1 5 6 4 ";
public static void main(String[] args) {
StringsCompare sc = new StringsCompare();
System.out.println(sc.compare(one, two));
}
private boolean compare(String one, String two) {
SortedSet<Integer> setOne = getSet(one);
SortedSet<Integer> setTwo = getSet(two);
return setOne.equals(setTwo);
}
private SortedSet<Integer> getSet(String str) {
SortedSet<Integer> result = new TreeSet<Integer>();
StringTokenizer st = new StringTokenizer(str, " ");
while (st.hasMoreTokens()) {
result.add(Integer.valueOf(st.nextToken()));
}
return result;
}
}
String.split
或 StringTokenizer
),然后将每个标记转换为数字。将字符串1中的所有数字放入 HashSet
中。对字符串2执行相同的操作。现在,您所要做的就是检查第一个 HashSet
中的每个条目是否也出现在第二个中。Integer.parseInt(One).intValue() == Integer.parseInt(two).intValue()
我不确定你想做什么,但我猜你最好使用数组。
NumberFormatException
。 - Bohemian