如何在给定的字符串中搜索Substring?

时间:2017-01-04 15:26:23

标签: java search hash substring

我想在不使用任何String API的情况下搜索给定STRING中的子字符串。我已尝试使用Hash Map但无法获得所需的输出。在这个例子中,我使用Hash Map完成了这个代码,如下所示。

  

输入=“面包黄油和面包”

     

输出=面包 - > 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");

}
}

但它没有按照我想要的方式工作,因为Hash Map可能无法实现。它从一开始就完成了单词的分割,以寻找那些重复出现的单词但是这个期望的输出我可能无法使用Hash Map,所以我已经写了一个更多的逻辑,如下所示。但它不是工作。你能帮我解决这些代码吗?    我想要的就像这样输出。

  

输入=“BreadbutterbreadButter”   输出=面包 - &gt; 2,黄油 - > 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);
        }                                         
    }

谢谢&amp;的问候,

PD

P.S:请不要在这篇文章中看到我的错误。这是我在这里的第一篇文章。

编辑:

我不想要任何已经开发的算法请看我的第二个代码我想用这种方法做。我想我非常接近答案,因为第二个代码我得到这样的结果

  

输入主字符串

     

输入&gt; ram ramram

     

输入要搜索的字符串

     

输出&GT; RAM

     

单词ram的频率为1

渴望输出&gt;但我希望ram为3。

0 个答案:

没有答案