Advertisement
dimipan80

7. Count Substring Occurrences

Sep 12th, 2014
235
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.08 KB | None | 0 0
  1. /* Write a program to find how many times given string appears in given text as substring.
  2.  * The text is given at the first input line.
  3.  * The search string is given at the second input line.
  4.  * The output is an integer number.
  5.  * Please ignore the character casing. */
  6.  
  7. import java.util.Scanner;
  8.  
  9. public class _07_CountSubstringOccurrences {
  10.  
  11.     public static void main(String[] args) {
  12.         // TODO Auto-generated method stub
  13.         Scanner scan = new Scanner(System.in);
  14.         System.out.println("Enter your target Text on single line:");
  15.         String inputText = scan.nextLine();
  16.         System.out.print("Enter your Word to search: ");
  17.         String searchStr = scan.next();
  18.  
  19.         String[] text = inputText.toLowerCase().split("[\\W]+");
  20.         searchStr = searchStr.toLowerCase();
  21.         int counter = 0;
  22.         for (String word : text) {
  23.             int indexSearch = word.indexOf(searchStr);
  24.             while (indexSearch >= 0) {
  25.                 counter++;
  26.                 indexSearch = word.indexOf(searchStr, indexSearch + 1);
  27.             }
  28.         }
  29.  
  30.         System.out.println("Given String appears in Given Text as Substring "
  31.                 + counter + " many times!");
  32.     }
  33.  
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement