Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C# Program to find number of occurrence of a character in a String
Let’s say our string is −
String s = "mynameistomhanks";
Now create a new array and pass it a new method with the string declared above. This calculates the occurrence of characters in a string.
static void calculate(String s, int[] cal) {
for (int i = 0; i < s.Length; i++)
cal[s[i]]++;
}
Let us see the complete code.
Example
using System;
class Demo {
static int maxCHARS = 256;
static void calculate(String s, int[] cal) {
for (int i = 0; i < s.Length; i++)
cal[s[i]]++;
}
public static void Main() {
String s = "mynameistomhanks";
int[] cal = new int[maxCHARS];
calculate(s, cal);
for (int i = 0; i < maxCHARS; i++) {
if (cal[i] > 1) {
Console.WriteLine("Character " + (char) i);
Console.WriteLine("Occurrence = " + cal[i] + " times");
}
if (cal[i] == 1) {
Console.WriteLine("Character " + (char) i);
Console.WriteLine("Occurrence = " + cal[i] + " time");
}
}
}
}
Output
Character a Occurrence = 2 times Character e Occurrence = 1 time Character h Occurrence = 1 time Character i Occurrence = 1 time Character k Occurrence = 1 time Character m Occurrence = 3 times Character n Occurrence = 2 times Character o Occurrence = 1 time Character s Occurrence = 2 times Character t Occurrence = 1 time Character y Occurrence = 1 time
Advertisements