[英]How do you find the amount of times a single character appears in a string and then store it into another string?
這是我現在擁有的代碼:
String dog = "my!cat!is!brown!so!what!";
String temp = "";
for(int i = 0; i <= dog.length(); i++) {
if(dog.charAt(i) == '!') {
temp+= "a";
}
}
我正在嘗試將其打印到可以打印“ 6”的位置,並且我不知道我是否朝錯誤的方向前進。 不要求代碼只是提示謝謝。
我會嘗試在您的for循環之前創建一個計數器。 然后,在每次要查找的字符出現時,增加計數器。
int j = 0; //Don't use i since it is your loop counter
//Each occurence:
j++;
然后在循環完成時將該int計數器轉換為您的字符串對象。
int count = StringUtils.countOccurrencesOf(dog, dog[i]);
if(temp.indexOf(dog[i])==-1)
{
temp+=dog[i]+": "+count+",";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.