简体   繁体   中英

How do you find the amount of times a single character appears in a string and then store it into another string?

here is the code I have right now:

String dog = "my!cat!is!brown!so!what!";
String temp = "";
for(int i = 0; i <= dog.length(); i++) {
    if(dog.charAt(i) == '!') {
        temp+= "a";
    }
}

I am trying to get it to the point where I can print "6" As and I don't know if I am heading in the wrong direction. Not asking for code just tips thanks.

I would try to create a counter prior to your for loop. Then on every occurence of the char you are looking for, increment the counter.

int j = 0; //Don't use i since it is your loop counter

//Each occurence:
j++;

Then convert that int counter to your string object when the loop is complete.

int count = StringUtils.countOccurrencesOf(dog, dog[i]);
if(temp.indexOf(dog[i])==-1)
{
    temp+=dog[i]+": "+count+",";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM