3. Given a string and substring, write a method that returns number of occurrences of substring in the string. Assume that both are case-sensitive. You may need to use library function here.
Expected input and output
HowManyOccurrences("do it now", "do") → 1
HowManyOccurrences("empty", "d") → 0
4. Write a program in C# Sharp to count a total number of duplicate elements in an array.
Test Data :
Input the number of elements to be stored in the array :3
Input 3 elements in the array
// 3.
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
internal class Program
{
public static int HowManyOccurrences(string str, string sub)
{
var count = 0;
var flag = false;
for (var i = 0; i < str.Length; i++)
{
var ch = str[i];
if (ch == sub[0])
{
for (var j = 1; j < sub.Length; j++)
if (i + j < str.Length)
if (str[i + j] != sub[j])
{
flag = true;
break;
}
if (!flag)
count++;
}
flag = false;
}
return count;
}
public static void Main(string[] args)
{
Console.WriteLine(HowManyOccurrences("This is sample sentenceis", "is"));
Console.WriteLine(HowManyOccurrences("empty", "d"));
}
}
}
// 4.
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
internal class Program
{
public static void Main(string[] args)
{
int[] arr = new int[100];
int i, j, num, count = 0;
Console.WriteLine("Input the number of elements to be stored in the array : ");
num = Convert.ToInt32(Console.ReadLine());
Console.WriteLine($"Input {num} elements in the array: ");
for (i = 0; i < num; i++)
{
arr[i] = Convert.ToInt32(Console.ReadLine());
}
for (i = 0; i < num; i++)
{
for (j = i + 1; j < num; j++)
{
if (arr[i] == arr[j])
{
count++;
break;
}
}
}
Console.WriteLine("\n Total number of duplicate elements found in array:"+count);
Console.ReadLine();
}
}
}
Comments
Leave a comment