我试图弄清楚如何计算String中某个字符的出现次数,以便连续出现被认为是一个。就像字符串" PPPPAPAAPP" P为3,A为2。
答案 0 :(得分:1)
我认为这会对你有帮助,
import java.util.*;
public class MyClass {
public static void main(String args[]) {
Map<String,Integer> countMap = new HashMap<String,Integer>();
String s = "PPPPPAAPAP";
String prev = null;
for(int i=0;i<s.length();i++){
String c = String.valueOf(s.charAt(i));
if(prev==null){
countMap.put(c,new Integer(1));
}else{
if(!c.equals(prev)){
if(countMap.containsKey(c)){
Integer count = countMap.get(c);
count = count +1;
countMap.put(c,count);
}
else{
countMap.put(c,new Integer(1));
}
}
}
prev = c;
}
for(String keys :countMap.keySet()){
System.out.println("Keys:"+keys+"\t"+countMap.get(keys));
}
}
}
答案 1 :(得分:0)
这会正确显示您的总数:
public static void main (String Args[]){
Scanner in =new Scanner(System.in);
String s =in.next();
//HashSet hd =new HashSet();
int flag=0;
int count=1;
char a=s.charAt(0);
for(int i=1;i<s.length();i++)
{
//hd.add(s.charAt(i));
if(a==s.charAt(i))
{
continue;
}
else
{
a=s.charAt(i);
count++;
}
}
System.out.println(count);
}
答案 2 :(得分:0)
如果你只需要打字或者例如限制范围ASCII
,那么您可以避免使用Map
:
public static void main(String... args) {
int[] letters = calcLetterGroups("PPPPPAAPAP");
printExistedLetterGroups(letters);
}
public static int[] calcLetterGroups(String str) {
int[] arr = new int['Z' - 'A' + 1];
char prv = '\0';
for (char ch : str.toUpperCase().toCharArray()) {
if (ch >= 'A' && ch <= 'Z' && prv != ch) {
arr[ch - 'A']++;
prv = ch;
}
}
return arr;
}
public static void printExistedLetterGroups(int... letters) {
for (char ch = 'A'; ch <= 'Z'; ch++)
if (letters[ch - 'A'] > 0)
System.out.printf("%s: %d\n", String.valueOf(ch), letters[ch - 'A']);
}