How to Count Occurrence of a given Character in a String in Java ?

Answer : The number of occurrences of each character to be count…

How to Count Occurrence of a given Character in a String in Java ?

  • The number of occurrences of each character to be count and also the occurrences of duplicate characters it should not be display repeatedly. The following steps are given below,
    • First, we split the strings by spaces.
    • Take a variable count = 0 and in every true condition we increment the count by 1.
    • Now run a loop at 0 to length of string.
    • And then check if our string is equal to the word.
    • If condition true then we increment the value of count by 1.

Sample Code in Java

[pastacode lang=”java” manual=”class%20wiki%7B%0A%09public%20static%20void%20main%20(String%5B%5D%20args)%20%7B%0A%09String%20str%20%3D%20%22Welcome%20to%20wikitechy%20website.%20Wikitechy%20is%20the%20best%20website%20to%20learn%20technology.%22%0AString%20findStr%20%3D%20%22wikitechy%22%3B%0Aint%20lastIndex%20%3D%200%3B%0Aint%20count%20%3D%200%3B%0A%0Awhile(lastIndex%20!%3D%20-1)%7B%0A%0A%20%20%20%20lastIndex%20%3D%20str.indexOf(findStr%2ClastIndex)%3B%0A%0A%20%20%20%20if(lastIndex%20!%3D%20-1)%7B%0A%20%20%20%20%20%20%20%20count%20%2B%2B%3B%0A%20%20%20%20%20%20%20%20lastIndex%20%2B%3D%20findStr.length()%3B%0A%20%20%20%20%7D%0A%7D%0ASystem.out.println(count)%3B%0A%09%7D%0A%7D” message=”” highlight=”” provider=”manual”/]

Output

2
Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like