字符串数组二进制搜索字符

时间:2014-01-30 06:08:52

标签: java binary

我有这个项目需要用户输入一个字符串然后你应该在字符串中搜索一个字符及其出现的次数。我在使用字符的二进制算法开始搜索过程时遇到了麻烦。这是我到目前为止所得到的:

package assignment3;

import java.util.Scanner;

public class charSearch{

    public static void main(String[] arg){

        Scanner thisString=new Scanner(System.in);

        System.out.println("Hello there! Please type in a few words and enter 'Done' when you are finished");

        String line=thisString.nextLine();

        String[] lineArray=line.split("\\ ");

        int lengthOfString=lineArray.length;

        String terminator="Done";

        String[] newArray=new String[lengthOfString-1];

        for(int i=0; i<lengthOfString-1; i++){

            if(lineArray[i]!=terminator){

                newArray[i]=lineArray[i];

                System.out.println(newArray[i]);

            }

        }

        int lengthOfArray=newArray.length;

    }

}

1 个答案:

答案 0 :(得分:0)

我认为如果我明白你想要得到的东西是什么东西呢?

package snippet;

import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Scanner;

public class Snippet {

public static void main(String[] arg) {

    countCharacters();
}

private static void countCharacters() {

    Scanner thisString = new Scanner(System.in);

    System.out.println("Hello there! Please type in a few words and enter 'Done' when you are finished");

    String line = "", lettersToSearchFrom = "";

    while (!("Done").equals(line)) {

        line = thisString.nextLine();

        lettersToSearchFrom += line;
    }

    thisString.close();

    //Since "Done" takes up 4 characters, it will be removed
    int beginPoint = lettersToSearchFrom.length()-4;
    int endPoint = lettersToSearchFrom.length();

    //Replaces the last line entered which is "Done" as its not part of the letters to search from
    char[] characters = lettersToSearchFrom.toLowerCase().substring(0,beginPoint).toCharArray();

    System.out.println(lettersToSearchFrom);

    HashMap<Character, Integer> map = new HashMap<Character, Integer>();

    //This is where the counting happens
    for (char key : characters) {

        if (map.containsKey(key)) {

            int frequency = map.get(key);
            frequency++;
            map.put(key, frequency);
        } else {
            map.put(key, 1);
        }

    }

    // Display frequency for each character ignoring case
    for (Entry<Character, Integer> item : map.entrySet()) {
        System.out.println(item.getKey() + " = " + item.getValue());
    }

    //To display the frequency of a specific character you can just retrieve from map
    //The following is if we searching specifically for "A" and not "a"
    //Please keep in mind that everything was made to lower case so a '0' should be return for value of "A"
    //since it is not contained

    int frequency = map.get("A")==null?0:map.get("A");

    System.out.println("Number of occurences for 'A' is "+frequency);

}
}