2013-04-25 77 views
-8

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

例如在字符串“图片质量很好的这台相机。” “质量”和“好”之间的距离是1。

+3

System.out.println(“1”); – Osiris 2013-04-25 05:19:43

+0

@Osiris哈哈,但没有道理。欧普举了一个例子来澄清问题。在这种情况下,你有点迂腐( - : – 2013-04-25 07:43:41

+0

因为它的功能就像一个家庭作业(我假设它是这样的),它是求代码而不是问,它也没有显示研究成果 – 2013-04-25 08:12:33

回答

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); 
} 
+0

Downvote!明智足以留下评论? – NINCOMPOOP 2013-04-25 05:33:08

+0

我没有downvote你,但我想这是因为你没有显示任何参数化,并通过标记整个字符串使用过于复杂的方法。 – 2013-04-25 07:50:40

+0

@Noob它的工作原理和感谢你这么多 – 2013-04-26 07:21:31

2
  1. 也许从String.split(...)开始获取所有单词的数组。
  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; 
    } 

有一个愉快的一天(其卓越的画质)!

+0

为什么你使用一个数组参数,当你期望正好两个单词? – 2013-04-25 08:11:46

+0

@Jacob你读我的思想,只是改变( - : – 2013-04-25 08:16:24

相关问题