Powered By Blogger

Friday, January 29, 2010

File word count, whitespace count,Word Matches in C#



load event()
{
string FPath = @"D:\x.docx";
string text = File.ReadAllText(FPath);
MatchWord(FPath,"TestWordTOCount");
}

public void MatchWord(string Fname, string WordToMatch)
{
int count;
StreamReader reader = File.OpenText(Fname);
string contents = reader.ReadToEnd();
MatchCollection matches = Regex.Matches(contents, WordToMatch);
count = matches.Count;
}

static int CountNonSpaceChars(string value)
{
///
/// Counts the number of non-whitespace characters.
/// It closely matches Microsoft Word 2007.
///

/// String you want to count non-whitespaces in.
/// Number of non-whitespace chars.

int result = 0;
foreach (char c in value)
{
if (!char.IsWhiteSpace(c))
{
result++;
}
}
return result;
}

static int CountChars(string value)
{

///
/// Return the number of characters in a string using the same method
/// as Microsoft Word 2007. Sequential spaces are not counted.
///

/// String you want to count chars in.
/// Number of chars in string.


int result = 0;
bool lastWasSpace = false;

foreach (char c in value)
{
if (char.IsWhiteSpace(c))
{
// A.
// Only count sequential spaces one time.
if (lastWasSpace == false)
{
result++;
}
lastWasSpace = true;
}
else
{
// B.
// Count other characters every time.
result++;
lastWasSpace = false;
}
}
return result;
}

No comments:

Post a Comment