Is there a simple way (instead of traversing manually all the string, or loop for indexOf) in order to find how many times, a character appears in a string?
Say we have "abdsd3$asda$asasdd$sadas" and we want that $ appears 3 times.
Use the count() Function to Count the Number of a Characters Occuring in a String in Python. We can count the occurrence of a value in strings using the count() function. It will return how many times the value appears in the given string. Remember, upper and lower cases are treated as different characters.
Step 1: Declare a String and store it in a variable. Step 2: Use 2 loops to find the duplicate characters. Outer loop will be used to select a character and initialize variable count to 1. Step 3: Inner loop will be used to compare the selected character with remaining characters of the string.
Take a string str. Take n as integer, ch as character and length of str as integer. Function occurrences_char(string str, int length, int n, char ch) takes str, ch, n and length of str and returns the count of ch in first n characters in repeated string str. Take the initial count as 0.
public int countChar(String str, char c) { int count = 0; for(int i=0; i < str.length(); i++) { if(str.charAt(i) == c) count++; } return count; }
This is definitely the fastest way. Regexes are much much slower here, and possible harder to understand.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With