2016-11-20 133 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

相关问题