Reputation: 459
I have two Strings that contain numbers and I want to see if the second string contains the same numbers as the first String, whether they are in order or not. If it has any number repeating than report false. Is there anyway in java other than using .charAt() because its not working for number after 10?
String one = "1 2 3 4 5 ";
String two = " 3 2 1 4 5 ";
String three = "3 2 1 4 4 ";
Upvotes: 5
Views: 4330
Reputation: 42143
Looks like homework. So these steps you can follow:
Upvotes: 7
Reputation: 306
I would at first parse numbers as integers, put them to the set and compare them:
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;
}
}
Upvotes: 0
Reputation: 63708
Try like this.
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);
Upvotes: 2
Reputation: 272802
I would not perform the comparison on the raw strings. Instead, first convert each String
to a List<Integer>
using String.split()
and Integer.parseInt()
on each result. Then sort()
the lists into ascending order, and then it becomes very easy to compare them.
Upvotes: 2
Reputation: 26586
You split the strings on whitespace (using either String.split
or StringTokenizer
) and then convert each of the tokens into a number. Place all the numbers in string one into a HashSet
. Do the same for string two. Now all you have to do is to check whether each entry in the first HashSet
also occurs in the second one.
Upvotes: 0
Reputation: 19187
You can use Scanner.nextInt()
to read numbers from the string, add them to a Set
, and see if set1.equals(set2)
is true.
Upvotes: 4
Reputation: 1297
You could tokenize/split the strings based on the spaces, then loop through the resulting tokens which would be the numbers themselves.
Upvotes: 0
Reputation: 2398
Try to parse the strings in int.
Integer.parseInt(One).intValue() == Integer.parseInt(two).intValue()
I'm not sure what you're trying to do but my guess is that you'd better to use arrays.
Upvotes: -1