Wednesday, May 6, 2009
WORD,LINE,CHARACTER COUNTER IN C#
static void Main(string[] args) {
string str = "hello world\nmy name is sumair\n IV";
int wordcount = 0,charcount = 0,linecount = 0;
//calculating first line
if (str != "")
{
linecount++;
}
for (int i = 0; i < 2; i++)
{
//calculating first and last word
if ((str[0] >= 97 && str[0] <= 122) || (str[str.Length - 1] >= 97 && str[0] <= 122))
{
wordcount++;
}
}
for (int i = 0; i < str.Length; i++)
{
if (str[i] == ' ')
{
wordcount++;
}
if ((str[i] >= 97 && str[i] <= 122) || (str[i] >= 65 && str[i] <= 91))
{
charcount++;
}
if (str[i] == '\n')
{
linecount++;
}
}
Console.WriteLine("Total words are : "+wordcount+"\nTotal characters are : "+charcount+"\nTotal lines are : " + linecount);
Console.ReadKey();
}
Subscribe to:
Posts (Atom)