As Brian said, Strings in java are immutable. This means that you can't assign through a method call like m2.charAt(j)=' '
.This means you have to use another way to keep track of whether you've found the character yet.
You could add it to intersection
and when checking a character make sure it isn't in intersection
by using intersection.indexOf(char c)
, if this returns -1 then it isn't in the string.
edit:
Sorry didn't put into account that the output should be a multiset. The above solves the problem if the output is a set.
You could use replaceFirst(String searchFor, String replacement)
on your m2 to delete it. it would be something like:
for( int i =0; i < m1.length(); i+=2)
{
if(m2.indexOf(m1.charAt(i)) != -1)
{
intersection = intersection + m1.charAt(1) + " ";
m2 = m2.replaceFirst(new String(m1.charAt(i)), "");
}
}
So if m1 = '1 1 2 3 5' and m2 = '1 4 2 1',
first pass: looks for 1 in '1 4 2 1'
second pass: looks for 1 in '4 2 1'
third pass: looks for 2 in '4 2'
fourth pass: looks for 3 in '4'
fifth pass: looks for 5 in '4'
returning '1 1 2'
Note that that it is incrementing the variable by two to take into account spaces. This is only if we assume that the two strings are in the form 'a a a a a a', with 'a' only being a single character. If there are digits or characters that are more than a digit long then you have to skip whitespace and interpret the string in a different way, other than just looking at it at a character-by-character basis.
If we can make these assumtions, it would be wise to trim your m1 of trailing and leading whitespace using the String trim
method ie m1 = m1.trim()
before executing this loop.