Access over 40 Millions of academic & study documents

9 Write a method int countDifferentChars(String s, String t) that c

Content type
User Generated
Showing Page:
1/3
9. Write a method int countDifferentChars(String s, String
t) that counts the number of corresponding characters of s
and t that don\'t match (are different). For example
countDifferentChars(\"abcxa\", \"abcdax\") would return 2
and countDifferentChars(\"xabc\", \"abcx\") would return 4.
Notice that if one string is longer than another, all the
additional characters count as non-matches.
Solution
/**
* @author
*
*/
public class CountDiffChars {
/**
* to count different characters, by comparing two strings
*
* @param s
* @param t
* @return
*/
public static int countDifferentChars(String s, String t) {
int count = 0;

Sign up to view the full document!

lock_open Sign Up
Showing Page:
2/3
int minLen = 0;
int sLen = s.length(), tLen = t.length();
// additional characters count as non-matches
if (sLen < tLen) {
count = tLen - sLen;
minLen = sLen;
} else {
count = sLen - tLen;
minLen = tLen;
}
for (int i = 0; i < minLen; i++) {
if (s.charAt(i) != t.charAt(i))
count++;
}
return count;
}
/**
* @param args
*/
public static void main(String[] args) {
System.out.println(\"Test 1:\" +
countDifferentChars(\"abcxa\", \"abcdax\"));
System.out.println(\"Test 2:\" +
countDifferentChars(\"xabc\", \"abcx\"));
}

Sign up to view the full document!

lock_open Sign Up
Showing Page:
3/3

Sign up to view the full document!

lock_open Sign Up
Unformatted Attachment Preview
9. Write a method int countDifferentChars(String s, String t) that counts the number of corresponding characters of s and t that don\'t match (are different). For example countDifferentChars(\"abcxa\", \"abcdax\") would return 2 and countDifferentChars(\"xabc\", \"abcx\") would return 4. Notice that if one string is longer than another, all the additional characters count as non -matches. Solution /** * @author * */ public class CountDiffChars { /** * to count different characters, by comparing two strings * * @param s * @param t * @return */ public static int countDifferentChars(String s, String t) { int count = 0; int minLen = 0; int sLen = s.length(), tLen = t.length(); // additional characters count as non -matches if (sLen < tLen) { count = tLen - sLen; minLen = sLen; } else { count = sLen - tLen; minLen = tLen; } for (int i = 0; i < minLen; i++) { if (s.charAt(i) != t.charAt(i) ...
Purchase document to see full attachment
User generated content is uploaded by users for the purposes of learning and should be used following Studypool's honor code & terms of service.
Studypool
4.7
Indeed
4.5
Sitejabber
4.4

Similar Documents