2016-11-23 12 views
-2

ユーザーが文字列を入力する配列を使用してプログラムを作成するには、x個の文字がいくつあるかを確認して合計単語数を出力します。例えば、ユーザが入力した場合:Javaカウント数単語の総数とその文字長

ユーザー539537グラムが

をcoolio8fsdさ

単語の数が6:"""USER""G"","coolio","fsd"である。このプログラムでは、文字以外のものを単語区切り文字とみなします。これは数字、記号、スペースです。

だから、プログラムが出力する必要があります

この文字列は、6つのワードの合計を持っています。

か1文字の単語

1つの2文字の単語

2つの3文字の単語

1つの4文字の単語

1つの6文字の単語

+0

出力を「2 3文字の単語」にすることはできますか? – bradimus

+0

この種の出力が必要な場合は、すべての数値の大きなマップを検討してください。それ以外の場合は、@bradimusの質問を、文字列の番号付けのために 'Strings'の代わりに' Integers'を使用するべきであるというアドバイスとして取ることができます。 –

答えて

0

文字列のsplitメソッドを正規表現で使用して、文字列を単語の配列(Strings)に分割し、次にco指定された長さの文字列をuntにします。

// 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")); 

私はこれを1行で行いましたが、読みやすさは低下しました。これは良いバランスのようです。

関連する問題