Extension Methods
CAMEL CASING
using System;
using System.Linq;
namespace TestProject
{
public static class StringExtensions
{
public static string ToCamelCase(this string value)
{
string[] strings = value.Split(' ');
var capitalisedText = strings[0].Substring(0, 1).ToLower() + strings[0].Substring(1).ToLower();
for (int i = 1; i < strings.Count(); i++)
{
capitalisedText += strings[i].Substring(0, 1).ToUpper() + strings[i].Substring(1).ToLower();
}
return capitalisedText;
}
}
internal class Program
{
static void Main(string[] args)
{
string original = "HellO world";
string camelCase = original.ToCamelCase();
Console.WriteLine(camelCase);
Console.ReadLine();
}
}
}
FINDING DUPLICATE COUNT
using System;
using System.Collections.Generic;
using System.Linq;
namespace TestProject
{
public static class StringExtensions
{
public static Dictionary<char, int> FindDuplicate(this string value)
{
Dictionary<char, int> keyValuePairs = new Dictionary<char, int>();
foreach (char c in value)
{
if (keyValuePairs.ContainsKey(c))
{
keyValuePairs[c]++;
}
else
{
keyValuePairs.Add(c, 1);
}
}
return keyValuePairs;
}
}
internal class Program
{
static void Main(string[] args)
{
string original = "Helloworld";
Dictionary<char, int> keyValuePairs = original.FindDuplicate();
foreach (var i in keyValuePairs)
{
Console.WriteLine(i);
}
Console.ReadLine();
}
}
}
FIND INDICES OF TWO NUMBERS WHICH ADDS UP TO TARGET NUMBER -
using System;
namespace TestProject
{
public static class StringExtensions
{
public static int[] FindIndices(this int[] arr, int target)
{
for (int i = 0; i < arr.Length - 1; i++)
{
for (int j = i+1; j< arr.Length; j++)
{
int result = arr[i] + arr[j];
if (result == target)
{
return new int[] { i,j };
}
}
}
return new int[] { };
}
}
internal class Program
{
static void Main(string[] args)
{
int[] arr = { 0, 7, 11, 2 };
int target = 9;
int[] indicesToFind = arr.FindIndices(target);
Console.WriteLine(String.Join(",",indicesToFind));
Console.ReadLine();
}
}
}
Find all prime numbers less than a given number n-
using System;
class Program
{
static bool FindPrime(int n)
{
if (n == 1)
{
return false;
}
if (n == 2)
{
return true;
}
if (n % 2 == 0)
{
return false;
}
for (int i = 3; i*i <= n; i++)
{
if (n % i == 0)
{
return false;
}
}
return true;
}
static void Main(string[] args)
{
int n = 20;
for (int i = 2; i < n; i++)
{
var isPrime = FindPrime(i);
if (isPrime)
{
Console.WriteLine(i);
}
}
Console.ReadLine();
}
}
Comments
Post a Comment