Java - Counting how many characters show up in another string
Posted
by
Vu Châu
on Stack Overflow
See other posts from Stack Overflow
or by Vu Châu
Published on 2012-03-24T21:36:33Z
Indexed on
2012/03/25
5:29 UTC
Read the original article
Hit count: 181
homework
I am comparing two strings, in Java, to see how many characters from the first string show up in the second string. The following is some expectations:
matchingChars("AC", "BA") ? 1
matchingChars("ABBA", "B") ? 2
matchingChars("B", "ABBA") ? 1
My approach is as follows:
public int matchingChars(String str1, String str2) {
int count = 0;
for (int a = 0; a < str1.length(); a++)
{
for (int b = 0; b < str2.length(); b++)
{ char str1Char = str1.charAt(a);
char str2Char = str2.charAt(b);
if (str1Char == str2Char)
{ count++;
str1 = str1.replace(str1Char, '0');
}
}
}
return count;
}
I know my approach is not the best, but I think it should do it. However, for
matchingChars("ABBA", "B") ? 2
My code yields "1" instead of "2". Does anyone have any suggestion or advice? Thank you very much.
© Stack Overflow or respective owner