2016-11-23 43 views
-2

如何使用数组在用户输入字符串时创建程序,它会检查多少字有x个字母,然后打印总字数。例如,如果用户输入:Java计数编号总字数及其字符长度

用户539537克被coolio8fsd

的字的数量为6:“该”“用户”“G”“是“,”coolio“,”fsd“。该程序认为任何非字母都是分隔符,这将是数字,符号和空格。

因此,该程序应该输出:

这串共有6个字。

一个1字母的单词

一个两字母字

两个3个字母的单词

一个4个字母的单词

一个6个字母的单词

+0

输出可以是“2个3个字母的单词”吗? – bradimus

+0

如果您想要这种输出,请考虑所有数字名称的大图。否则,您可以将@bradimus问题作为一个建议,例如,如果使用“字符串”来表示外观编号,则应该使用“整数”。 –

回答

0

您可以使用带正则表达式的字符串拆分方法将字符串拆分为字串数组(字符串),然后co解决具有指定长度的字符串问题。

// This regex finds all sequences of whitespace and numerical digits 
s.split("\\s*[^A-z]\\s*|[\\s]+"); 
0

流将在这里工作。

// I'm assuming you can get the input from somewhere 
// maybe a scanner 
String input = "The user 539537g is coolio8fsd"; 

// Split on any non-letter 
String[] words = input.split("[^A-z]"); 

Map<Long, Long> wordCounts = 
    Arrays.stream(words)       // Stream the words 
      .filter(s -> !s.isEmpty())    // Filter out the empty ones 
      .map(String::length)      // Map each string to its length 
      .collect(Collectors.groupingBy(i->i, Collectors.counting()); // Create a map with length as key and count as value 

System.out.println("There are " + wordCounts.size() + " words."); 
wordCounts.forEach((k,v) -> System.out.println(v + " " + k + "-letter words")); 

我确实设法在一行中做到这一点,但可读性降低了。这似乎是一个很好的平衡。