2016-11-20 129 views
0

我想統計「用戶」輸入的數組中出現的次數並將其存儲在變量中命名爲「theCount」。我用for循環遍歷數組,並用if語句檢查「the」。如何將字符串中的單詞分成兩個令牌(如果它包含較小的單詞)

我不允許使用正則表達式。

這是我到目前爲止有:

import java.util.*; 

public class theCount 
{ 
    public static void main (String[] args) 
    { 
     Scanner userInput = new Scanner(System.in); 

     System.out.print("Enter a sentence: "); 
     String sentence = userInput.nextLine(); 

     String[] input = sentence.split(" the"); 

     int theCount = 0; 

     for (String token : input) { 
      if (token == "the") 
       theCount++; 
       System.out.print("\n" + theCount); //I want it printed after 
                //iteration. 

     } 




    } 


} 
+0

將'System.out.print ...'移出for循環的括號,並將'the'前面的空格拆分 – Yazan

+3

如果split()導致字符串被拆分,你已經知道「the」已被找到。只需輸出「input.length - 1」作爲「the」的計數。無需循環。 –

回答

1

有兩個問題:

  1. split(" the")使用" the"爲分隔符,並給出了的話休息。最好的是使用空格分割。使用token.equals("the")代替==
0

如果要統計出現次數使用此示例代碼:

import java.util.*; 
public class theCount { 
    public static void main(String[] args) { 
     Scanner userInput = new Scanner(System.in); 
     System.out.print("Enter a sentence: "); 
     String sentence = userInput.nextLine(); 
     int theCount = sentence.length() - sentence.replace("the", "").length(); 
     System.out.print("Number of occurrence: " + theCount); 
    } 
} 
+0

爲了得到單詞在程序中出現的次數,我需要將計數除以三,由於您的公式計算了字符串中出現次數't','h'和'e'的次數。 –

0

您可以輸入添加到一個數組列表,然後可以發揮與它周圍。

一種方法是從頻率方法獲得計數。

List<String> arrayList = new ArrayList<String>(); 
arrayList.add("String"); //add all the words. 

Collections.frequency(arrayList, "the"); 

第二種方法是從地圖中獲取計數。

Map<String, Integer> map = new HashMap<String, Integer>(); 
for(String s : arrayList){ 
     Integer count = map.get(s); 
     map.put(s, count==null?1:count+1); 
} 
//the below will give you the count of any word. 
map.get("the"); 
0

從Java 8開始,你可以通過stream api來解決這個問題。這將更加簡潔。看看下面的代碼示例

public static void main(String[] args) { 
    String str = "The is the for THE and the the the the The The"; 

    long count = Stream.of(str.split(" ")) 
      .filter(i -> i.equalsIgnoreCase("the")) 
      .count(); 

    System.out.println(count); 
} 

===更新===

public static void main(String[] args) { 

    String str = " there these theology"; 

    long count = Stream.of(str.split(" ")) 
      .map(String ::toLowerCase) 
      .filter(i -> i.contains("the")) 
      .count(); 

    System.out.println(count); 
} 

===更新===

該解決方案將工作,即使有多個相同字符串中的子字符串。

public static void main(String[] args) { 

    String str = " thesethefajfskfjthetheasdfjasdkfjthe"; 
    String findStr = "the"; 

    int count = 0; 
    for (String s : str.split(" ")) { 
     count += s.toLowerCase() 
       .split(findStr, -1).length - 1 ; 
    } 

    System.out.println(count); 

} 

This SO帖子將幫助你瞭解,如何找到一個字符串的所有子字符串。

+0

這個工作是否會像那裏的神學一樣?由於'the'中的字母在他們之內。 –

+0

@Jason_Silva我已經更新了我的答案。查看更新部分。這應該符合您的要求。爲了獲得更多的許可,你是否還需要考慮那些是另一個詞的子字符串的「單詞」?像'kdfasfjTHEkfskf'這個詞包含一個作爲子字符串。 – seal

+0

@Jason_Silva查看最近更新的部分。 – seal

相關問題