-8

Java プログラムを作成して、文字列 (距離) 内の 2 つの単語の間に含まれる単語数を判断したいと考えています。

たとえば、文字列で「このカメラの画質は素晴らしいです。」「品質」と「素晴らしい」の間の距離は 1 です。

4

3 に答える 3

2
  1. おそらく String.split(...) から始めて、すべての単語の配列を取得します。
  2. 次に、配列で両方の単語を検索できます。両方の単語のインデックスがわかれば、距離を判断できます。
于 2013-04-25T05:22:07.393 に答える
1

ポインタだけで、コードを最適化できます。

public static void main(String[] args) {
    String str = "The picture quality is great of this camera";
    StringTokenizer st = new StringTokenizer(str);
    int numberOfWords = 0;
    boolean start = false;
    while(st.hasMoreTokens()){
        String token = st.nextToken();
        if(token.equals("quality")){
            start = true;
            continue;
        }
        if(start) {
            if(token.equals("great")){
                start = false;
            }
            else {
                numberOfWords++;
            }
        }

    }
    System.out.println(numberOfWords);
}
于 2013-04-25T05:27:44.367 に答える
0

これが私の解決策です:

    public static void main(String[] args) {

        String input = "The picture quality is great of this camera";

        // happy flows
        System.out.println(findDistance(input, "quality", "great"));
        System.out.println(findDistance(input, "picture", "of"));

        // words in reversed order
        System.out.println(findDistance(input, "camera", "great"));

        // non occurring words
        try {
            System.out.println(findDistance(input, "picture", "camcorder"));
        }
        catch(IllegalArgumentException e) {
            System.out.println("Expected exception caught, message was: " + e.getMessage());
        }
    }

    private static int findDistance(String input, String word1, String word2) {
        // check input
        if (input == null) {
            throw new IllegalArgumentException("Input cannot be null");
        }
        if (word1 == null || word2 == null) {
            throw new IllegalArgumentException("Two words should be provided");
        }

        // determine boundaries
        int pos1 = input.indexOf(word1);
        int pos2 = input.indexOf(word2);

        // check boundaries
        if (pos1 < 0 || pos2 < 0) {
            throw new IllegalArgumentException("Both words should occur in the input");
        }

        // swap boundaries if necessary to allow words in reversed order
        if (pos1 > pos2) {
            int tmp = pos1;
            pos1 = pos2;
            pos2 = tmp;
        }

        // obtain the range between the boundaries, including the first word
        String range = input.substring(pos1, pos2);

        // split the range on whitespace
        // minus one to not count the first word
        return range.split("\\s").length - 1;
    }

良い一日を(素晴らしい画質です)!

于 2013-04-25T08:08:00.880 に答える