Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple way to count character occurrences in a string [duplicate]

Tags:

java

string

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.

like image 553
George Kastrinis Avatar asked May 23 '11 17:05

George Kastrinis


People also ask

How do you count specific occurrences of characters in a string?

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.

How do you count repeated elements in a string Python?

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.

How do I count the number of repeated characters in a string in C++?

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.


1 Answers

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.

like image 125
Daniel Avatar answered Sep 29 '22 11:09

Daniel