- Back to Home »
- C#.NET »
- C# Code to print how many times a character is present in a string
Posted by :
Sudhir Chekuri
Sunday, 6 October 2013
Task: Write a program to print the number of times a character is present in a string.
For example display the number of times 'a' is present in 'arshadmohammed'.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string s = "arshadmohammod";
char[ ] c = s.ToCharArray( );
int count = 0;
foreach (char ch in c)
{
if (ch == 'a')
{
count++;
}
}
Console.WriteLine("no of times a repeated is :"+count);
Console.ReadKey( );
}
}
}
Output
3
Explanation
above program contains a string variable s which contain "arshadmohammod"
In the above string a is repeated 3 times arshadmohammod
That string is divided into an array of characters using method ToCharArray( ) . -
char[ ] c = s.ToCharArray( );
count is a variable of int type intialized with zero used to count no of a's repeated in the string.
using for each loop all elements in char array are stored into ch one by one and repeatedly checked using if condition.
if (ch == 'a')
{
count++;
}
if element matched with a then count is incremented by one.
after the foreach loop the number in count variable is printed as output.
For example display the number of times 'a' is present in 'arshadmohammed'.
C# Code to print how many times a character is present in a string
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string s = "arshadmohammod";
char[ ] c = s.ToCharArray( );
int count = 0;
foreach (char ch in c)
{
if (ch == 'a')
{
count++;
}
}
Console.WriteLine("no of times a repeated is :"+count);
Console.ReadKey( );
}
}
}
Output
3
Explanation
above program contains a string variable s which contain "arshadmohammod"
In the above string a is repeated 3 times arshadmohammod
That string is divided into an array of characters using method ToCharArray( ) . -
char[ ] c = s.ToCharArray( );
count is a variable of int type intialized with zero used to count no of a's repeated in the string.
using for each loop all elements in char array are stored into ch one by one and repeatedly checked using if condition.
if (ch == 'a')
{
count++;
}
if element matched with a then count is incremented by one.
after the foreach loop the number in count variable is printed as output.