重複の可能性:
一意の各文字の出現回数をカウントする
文字列内の各文字の出現回数を取得するにはどうすればよいですか? 例えば:
"stackoverflow": s:1 t:1 a:1 c:1 k:1 o:2 v:1 e:1 r:1 f:1 l:1 o:1 w:1
重複の可能性:
一意の各文字の出現回数をカウントする
文字列内の各文字の出現回数を取得するにはどうすればよいですか? 例えば:
"stackoverflow": s:1 t:1 a:1 c:1 k:1 o:2 v:1 e:1 r:1 f:1 l:1 o:1 w:1
グアバを救え!信じられない、これが Java ワンライナーだ!
Multiset<Character> distintCharsAndCount = HashMultiset.create(
Chars.asList("ssssssssstackoverflow".toCharArray())
);
Chars.asList は、文字列を非プリミティブの実際のコレクションに変換するのに役立ちます。MultiSet は、あなたが求めているものに最適な構造です。これは、個別の要素を保持する Set ですが、セット内の出現回数も保持します。
次の方法でアクセスします。
int sCount = distintCharsAndCount.count('s'); //sets it to 9
キーを Character として、Integer カウントを値として HashMap を作成します。
HashMap<Character, Integer> hm = new HashMap<Character, Integer>()
for (int i = 0; i < str.length; i++) {
if (hm.get(str.charAt(i))) {
int temp = hm.get(str.charAt(i));
hm.put(str.charAt(i), ++temp);
} else {
hm.put(str.charAt(i), 1);
}
}
私が過去にこれを行った単純ですが直感的な方法は、charsをintとしてキャストしてから、配列を使用することです。マップを使用することはより良いアプローチですが、これは宿題の問題のように聞こえ、キャストと配列を使用することは初心者にとってもう少し論理的(imo)です。
int counts[] = new int[26];
String s = 'stackoverflow';
s = s.toLowerCase();
for (int i = 0; i < s.length(); i++) {
int val = (int)(s.charAt(i)) - 97;
counts[val]++;
}
文字からカウントへのマップを使用し、マップまたはカウントに追加する文字配列を反復処理することをお勧めします。
Map<Character, Integer> chars = new HashMap<Character, Integer>();
for (int i = 0; i < str.length; i++) {
char c = str.charAt(i);
Integer count = chars.get(c);
if (count == null) {
chars.put(c, 1);
} else {
chars.put(c, count + 1);
}
}
String input = "stackoverflow";
// desired output: s:1 t:1 a:1 c:1 k:1 o:2 v:1 e:1 r:1 f:1 l:1 o:1 w:1
Map<Character,Integer> counts = new HashMap<Character, Integer>
( Math.min(input.length(),Character.MAX_VALUE) / 2 );
char ch;
for (int i=0; i<input.length(); ++i)
{
ch = input.charAt(i);
if ( !counts.containsKey(ch)) { counts.put(ch,0); }
counts.put(ch, counts.get(ch)+1 );
}
for (Map.Entry<Character,Integer> entry : counts.entrySet() )
{
out.print( entry.getKey() );
out.print( ":" );
out.print( entry.getValue());
out.print( " " );
}
public static Map<Character, Integer> count(String s) {
Map<Character, Integer> result = new HashMap<Character,Integer>();
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
Integer n = result.get(c);
result.put(c, n == null ? 1 : n + 1);
}
return result;
}
文字列を解析して a を作成Map<Character, Integer>
し、整数(マップ内の値) が文字c (マップ内のキー) が文字列内に出現する回数を表すようにすることができます。