2013-04-25 78 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

相關問題