I want to search sub string in given STRING without using any String API . I have tried with Hash Map but not able to get desired output . In this example i have done code for this using Hash Map, which is as following .
Input = "Bread butter and bread"
Output = bread -> 2
import java.util.HashMap;
import java.util.Set;
public class WordCount
{
static void duplicateWords(String inputString)
{
//Splitting inputString into words
String[] words = inputString.split(" ");
//Creating one HashMap with words as key and their count as value
HashMap<String, Integer> wordCount = new HashMap<String, Integer>();
//Checking each word
for (String word : words)
{
//whether it is present in wordCount
if(wordCount.containsKey(word.toLowerCase()))
{
//If it is present, incrementing it's count by 1
wordCount.put(word.toLowerCase(), wordCount.get(word.toLowerCase())+1);
}
else
{
//If it is not present, put that word into wordCount with 1 as it's value
wordCount.put(word.toLowerCase(), 1);
}
}
//Extracting all keys of wordCount
Set<String> wordsInString = wordCount.keySet();
//Iterating through all words in wordCount
for (String word : wordsInString)
{
//if word count is greater than 1
if(wordCount.get(word) > 1)
{
//Printing that word and it's count
System.out.println(word+" : "+wordCount.get(word));
}
}}
public static void main(String[] args)
{
duplicateWords("Bread butter and bread");
}
}
But it is not working as i have wanted because it might not be possible with Hash Map . It have done splitting of words from the start, to look out for those re-occurring words But this desired output i might not able to get with Hash Map so i have written one more logic for that which is as following .Still it is not working . Can you please help me with these codes ?. What i want is output like this .
Input = "BreadbutterbreadButter" Output = bread -> 2 , butter ->2
package string;
import java.util.Scanner;
public class SearchString {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println("enter main string");
String s = scan.nextLine();
System.out.println("enter string to be searched");
String f = scan.nextLine();
s = s + " ";
int l = s.length();
char a;
int c = 0;
String s1 = "";
for (int i = 0; i < l; i++) {
a = s.charAt(i);
if (a != ' ') {
s1 = s1 + a;
} else {
if (s1.equalsIgnoreCase(f) == true) {
c++;
}
s1 = "";
}
}
System.out.println("Frequency of the word " + f + " is " + c);
}
}
Thanks & Regards,
PD
P.S : Please don't see my mistakes in this post . It is my first post here .
Edited :
i don't want any already developed algorithm please see my second code i want to do it by that approach .I think i'm very close to the answer as for second code i'm getting result like this
enter main string
Input >ram ramram
enter string to be searched
Output>ram
Frequency of the word ram is 1
DESIRED OUTPUT >but i want ram to be 3 .