I would like to count of each unique letter in a string by using c#.net
I would like to write a problem to read a text file from command line and to output the count of each unique letter, sorted a开发者_如何转开发lphabetically. Any suggestions for this program in C# Example :
Stack overflows
Output :
a 1 c 1 k 1 t 1 s 2
As others have said, it sounds like homework. I'll just give you some hints:
- Split the task up. There's no need for the "processing" code to depend on the input coming from a file, or the output going to the screen.
- If you're allowed to, look at LINQ which provides sorting, grouping and counting functionality in a very easy-to-use way.
- For bonus points, implement unit tests for the processing part...
Using LINQ, one way to get the unique characters is:
string s = "Stack Overflows";
var x = from c in s.ToLower()
group c by c into a
select new { a.Key, Count = a.Count() };
string s = "stack overflows";
Dictionary<char, int> dic = new Dictionary<char, int>();
foreach (char x in s)
{
if (dic.ContainsKey(x) == true)
{
dic[x] += 1;
}
else
{
dic.Add(x, 1);
}
}
foreach (KeyValuePair<char, int> x in dic)
{
Console.WriteLine(x.Key + " " + x.Value);
}
class Test {
static void Main(string[] args)
{
string inputstring = "stackOverflows";
charcount(inputstring, inputstring.ToCharArray()[0]);
}
public static void charcount(string recstring ,char c )
{
if (recstring.Length != 0)
{
int count = 0;
foreach (char c1 in recstring)
{ if (c1==c)
{
count++;
}
}
Console.WriteLine(c+" "+count);
string tempstring = recstring.Replace(char.ToString(c), "");
if (tempstring.Length != 0)
{
charcount(tempstring, tempstring.ToCharArray()[0]);
}
}
}
精彩评论