簡體   English   中英

您如何查找單個字符出現在字符串中然后存儲到另一個字符串中的次數?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM