count occurrences of character in string code example

Example 1: count occurrences of character in string c++

std::string s = "a_b_c";
size_t n = std::count(s.begin(), s.end(), '_'); // n=2

Example 2: python return number of characters in string

# Example usage:
your_string = "Example usage"
len(your_string)
--> 13

Example 3: count characters in string python

>>> sentence = 'Mary had a little lamb'
>>> sentence.count('a')
4

Example 4: python count character occurrences

str1.count("a")

Example 5: count number of occurrences of character in string

public class CountStringOccurence {
public static void main(String[] args) {

int count= countOccurences("aaassssddadad",'s');
System.out.println(count);

}

private static int countOccurences(String word, char character){
  
  int count = 0;
  for(int i = 0; i < word.length(); i++){
    
    if(word.chartAt(i) == character){
      
      count++; } 
                 }
      return count;
}
}

Example 6: number of occurence in string

public class StringNumberOfOccurenceLetter {

    private static int countOccurences(String word, char character){

        int count = 0;
        for (int i = 0; i < word.length() ; i++) {
            if (word.charAt(i)==character){
                count++;
            }
        }
        return count;

    }
         public static void main(String[] args) {


        int count = countOccurences("dddssad", 'a');
    }

}

Tags:

Java Example