C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Next: This example iterates over its string parameter. Word 2007 counts ten spaces in a row as one—we do the same here.
And: The bool flag variable keeps track of whether the previous char was a space.
BoolInfo: We use the char.IsWhiteSpace method. This method handles newlines, line breaks, tabs and any whitespace.
CharMethod that counts characters: C#
/// <summary>
/// Return the number of characters in a string using the same method
/// as Microsoft Word 2007. Sequential spaces are not counted.
/// </summary>
/// <param name="value">String to count chars.</param>
/// <returns>Number of chars in string.</returns>
static int CountChars(string value)
{
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;
}
Method that counts word characters: C#
/// <summary>
/// Counts the number of non-whitespace characters.
/// It closely matches Microsoft Word 2007.
/// </summary>
/// <param name="value">String to count non-whitespaces.</param>
/// <returns>Number of non-whitespace chars.</returns>
static int CountNonSpaceChars(string value)
{
int result = 0;
foreach (char c in value)
{
if (!char.IsWhiteSpace(c))
{
result++;
}
}
return result;
}
File tested: decision.txt
Microsoft Word char count: 834
Method count: 830 [off by 4]
Word non-whitespace count: 667
Method count: 667 [exact]
Note: The methods are fairly fast because no StringBuilder appends or other string copying is done.
StringBuilderAnd: Scanning through individual characters was fast in my research. The foreach-loop is not slower than a for-loop.
ForeachFor