找出String中两个特定单词之间的距离

时间:2013-04-25 05:18:16

标签: java

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

例如在字符串中“图像质量非常好”。 “质量”和“伟大”之间的距离是一个。

3 个答案:

答案 0 :(得分:2)

  1. 也许从String.split(...)开始获取所有单词的数组。
  2. 然后您可以在数组中搜索这两个单词。你知道两个单词的索引就可以确定距离。

答案 1 :(得分: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);
}

答案 2 :(得分: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;
    }

度过愉快的一天(图片质量很好)!