Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class StringCounter {
- public static void main(String[] args) {
- String input = args[0];
- String target = args[1];
- System.out.println("Count: " + StringCount(input, target));
- }
- public static int StringCount(String input, String target) {
- if (input == null || input.isEmpty()) // Null/Empty check prevents infinite loop.
- return 0;
- else if (input.length() == 1) { // Last character in the input string
- if (input.equals(target))
- return 1;
- else
- return 0;
- } else { // Recursive calls checking the first character of the intput string
- if (input.substring(0, 1).equals(target))
- return 1 + StringCount(input.substring(1), target);
- else
- return StringCount(input.substring(1), target);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment