Objective of posting this question is to get ideas of experts if there is any better way of write the belowThis program?
Program is to count counts the total number of times any character from the source string can be found in the target string.
E.g Source String - "Hello World"
.
Target String - "llo"
Output = 5
(as there are 3 l
's and 2 o
's)
Source String - "Hello World"
Target String - "ooood"
Output = 3
(as there are 2 o
's and 1 d
)
Is there any better way of write the below program?
public class CountOccurence {
public static int countChars(String target, String source){
char a[] = source.toCharArray();
int loc = 0, count = 0;
boolean charRepeat = false;
for (loc = 0; loc < source.length(); loc++) {
charRepeat = false;
for (int z = 0; z < loc; z++) {
if (a[loc] == a[z]) {
charRepeat = true;
break;
}
}
if (charRepeat == false) {
int i = 0;
while ((i = target.indexOf(a[loc], i)) != -1) {
count++;
i++;
}
}
}
return count;
}
public static void main(String[] args) {
String target = "Hello World";
String source = "oood";
int count = countChars(target, source);
System.out.println(count);
source = "lld";
count = countChars(target, source);
System.out.println(count);
}
}