Hai sir...
Please help me to solve this...
Findout occurances of each string in every another string (built - in functions are not at all allowed)
all, and, sand, falling wall and sand
Here is a java example that finds the occurrences of each string in every another string.
class Occurrence { public static void main(String[] args) { String str = "all and sand falling wall and sand"; String findStr = "and"; int lastIndex = 0; int count = 0; while ((lastIndex = str.indexOf(findStr, lastIndex)) != -1) { count++; lastIndex += findStr.length() - 1; } System.out.println(findStr+" occurs " +count+ " times"); } }
Here is another code.
import java.util.*; public class CountWordOccurrence { public static void main(String[] args){ String[] st = {"all","and","sand","falling wall","and","sand"}; HashMap<String, Integer> map = new HashMap<String, Integer>(); String str=""; for(int i=0;i<st.length;i++){ str+=st[i]+" "; } str = str.toLowerCase(); int count = -1; for (int i = 0; i < str.length(); i++) { if ((!Character.isLetter(str.charAt(i))) || (i + 1 == str.length())) { if (i - count > 1) { if (Character.isLetter(str.charAt(i))) i++; String word = str.substring(count + 1, i); if (map.containsKey(word)) { map.put(word, map.get(word) + 1); } else { map.put(word, 1); } } count = i; } } ArrayList<Integer> list = new ArrayList<Integer>(); list.addAll(map.values()); Collections.sort(list, Collections.reverseOrder()); int last = -1; for (Integer i : list) { if (last == i) continue; last = i; for (String s : map.keySet()) { if (map.get(s) == i) System.out.println(s + ":" + i); } } } }
Ads