Count String using C#

Count space

int countSpaces = mystring.Count(Char.IsWhiteSpace);

Count Character in a string

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;
}
 
 
counts non-whitespace characters. 

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

Comments

Popular posts from this blog

Tree view in winforms using c#

how to Replace null value with 0 Using C#

how to fetch all HTML Table Records and modify all records accordingly using jquery and Javascript