Guest User

StringCounter

a guest
Mar 31st, 2014
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.75 KB | None | 0 0
  1. public class StringCounter {
  2.  
  3.     public static void main(String[] args) {
  4.         String input = args[0];
  5.         String target = args[1];
  6.  
  7.         System.out.println("Count: " + StringCount(input, target));
  8.     }
  9.  
  10.     public static int StringCount(String input, String target) {
  11.  
  12.         if (input == null || input.isEmpty()) // Null/Empty check prevents infinite loop.
  13.             return 0;
  14.         else if (input.length() == 1) { // Last character in the input string
  15.             if (input.equals(target))
  16.                 return 1;
  17.             else
  18.                 return 0;
  19.         } else { // Recursive calls checking the first character of the intput string
  20.             if (input.substring(0, 1).equals(target))
  21.                 return 1 + StringCount(input.substring(1), target);
  22.             else
  23.                 return StringCount(input.substring(1), target);
  24.         }
  25.     }
  26. }
Advertisement
Add Comment
Please, Sign In to add comment