Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count specific character occurrences in a string

Tags:

string

vb.net

What is the simplest way to count the number of occurrences of a specific character in a string?

That is, I need to write a function, countTheCharacters(), so that

str = "the little red hen" count = countTheCharacters(str,"e") ' Count should equal 4 count = countTheCharacters(str,"t") ' Count should equal 3 
like image 360
Urbycoz Avatar asked Mar 04 '11 12:03

Urbycoz


People also ask

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

Let's start with a simple/naive approach: String someString = "elephant"; char someChar = 'e'; int count = 0; for (int i = 0; i < someString. length(); i++) { if (someString. charAt(i) == someChar) { count++; } } assertEquals(2, count);

How do you count a string occurrence in a string?

First, we split the string by spaces in a. Then, 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 check if our string is equal to the word.

How do you count letters in a string in Python?

In Python, you can get the length of a string str (= number of characters) with the built-in function len() .


1 Answers

The most straightforward is to simply loop through the characters in the string:

Public Function CountCharacter(ByVal value As String, ByVal ch As Char) As Integer   Dim cnt As Integer = 0   For Each c As Char In value     If c = ch Then        cnt += 1     End If   Next   Return cnt End Function 

Usage:

count = CountCharacter(str, "e"C) 

Another approach that is almost as effective and gives shorter code is to use LINQ extension methods:

Public Function CountCharacter(ByVal value As String, ByVal ch As Char) As Integer   Return value.Count(Function(c As Char) c = ch) End Function 
like image 66
Guffa Avatar answered Sep 21 '22 10:09

Guffa