-8

我想编写一个 Java 程序来确定字符串中两个给定单词之间有多少个单词(距离)。

例如在字符串“这台相机的图像质量很棒”中。“质量”和“伟大”之间的距离是一。

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 回答