Interviews5 answers
I Have a string Like "nitin" Write to method or logic to get output like n=2 i=2 t=1
5 Answers
using linq.
class Program
{
static void Main(string[] args)
{
//int cnt = 0; int occ = 0;
Console.WriteLine("Enter string");
string str = Console.ReadLine();
char[] newstr = str.Distinct().ToArray();
for (int i = 0; i < newstr.Length; i )
{
Console.WriteLine(" {0} = {1} ", newstr[i], str.Count(x => x == newstr[i]));
}
Console.ReadLine();
}
}
Vaibhav SalwePosted May 30, 2015, 4:31 AM EDT
string str = "nitin";
var Mylsit = str.GroupBy(e => e).Select(g => new { g.Key, Count = g.Count() }).ToList();
Console.WriteLine(Mylsit[0]);
Console.WriteLine(Mylsit[1]);
Console.WriteLine(Mylsit[2]);
Pankaj Kumar ChoudharyPosted May 27, 2015, 8:58 AM EDT
// For basic understanding (code tested)
string str = "nitin";
int dynLength = str.Length;
int i = 0, j = 1, c = 0; ;
for (i = 0; i <= dynLength; i++)
{
for (j = 0; j < str.Length; j++)
{
if(str[0] == str[j]) // determining the occurances
{
c = c + 1;
}
}
Console.WriteLine(str[0] + " : " + c); // print the character with no. of occurances
str = str.Replace(str[0].ToString(),""); // remove character which is already counted;
dynLength = str.Length; // set dynamic length after remove counted character
c = 0;
i = 0;
}
Console.ReadLine();
Md. Raskinur RashidPosted Jan 10, 2015, 6:12 AM EST
string str = "nitin";
char[] arr = str.ToCharArray();
Dictionary d = new Dictionary();
for (int i = 0; i < arr.Length; i++)
{
if (d == null)
{
d.Add(arr[i].ToString(), 1);
}
else
{
if (d.ContainsKey(arr[i].ToString()))
{
d[arr[i].ToString()] = d[arr[i].ToString()] + 1;
}
else
{
d.Add(arr[i].ToString(), 1);
}
}
}
foreach (var s in d)
{
Console.WriteLine(s.Key + "=" + s.Value);
}
Sudhanshu PandeyPosted Jan 8, 2015, 6:26 AM EST
string input = "nitin";
var resultList = input.GroupBy(e => e).Select(g => new { g.Key, Count = g.Count() }).ToList();
Jitendra KumarPosted Dec 11, 2014, 6:01 PM EST


