Thursday, February 13, 2020

write a C# program to find number of occurences of a character in string

Using For Loop:

public class Program
    {
        public static void Main(string[] args)
        {
            string input = "Software@Solutions@Pvt$limited";

            while (input.Length > 0)
            {
                Console.Write(input[0] + " : ");
                int count = 0;
                for (int j = 0; j < input.Length; j++)
                {
                    if (input[0] == input[j])
                    {
                        count++;
                    }
                }
                Console.WriteLine(count);
                input = input.Replace(input[0].ToString(), string.Empty);
            }
            Console.ReadLine();
        }
    }

or

string  strconst="Software@Solutions@Pvt$limited";

var obj = strconst.GroupBy(x => x).Select( x =>new
{
Key= x.Key.ToString(),
Value = x.Count()
}).ToDictionary(t=>t.Key,t=>t.Value);
}
foreach (var t in obj)
{
Console.WriteLine($”{t.Key} has occurred {t.Value} times “);
}


Output:
S:3
O:3
F:1
t:3
w:1
a:1
r:1
e:2
@:2
l:2
u:1
i:3
n:1
p:1
v:1
$:1
m:1
d:1



No comments:

Post a Comment