How to count the white spaces in a string in C#

2 Answers

0 votes
using System;

public class CountWhiteSpacesInString_CSharp
{
    public static void Main(string[] args)
    {
        string s = "C# \n  Programming \r Language \t ";

        int WhiteSpaces = s.Length - s.ToLower().Replace(" ", "").Replace("\r", "").Replace("\n", "").Replace("\t", "").Length;

        Console.WriteLine("WhiteSpaces = " + WhiteSpaces);
    }
}


/*
run:
   
WhiteSpaces = 10
   
*/

 



answered Oct 19, 2024 by avibootz
0 votes
using System;

public class CountWhiteSpacesInString_CSharp
{
    static int countWhitespaceCharacters(string s) {
        int count = 0;
        
        foreach (char c in s) {
            if (char.IsWhiteSpace(c)) {
                count++;
            }
        }
        
        return count;
    }
    
    public static void Main(string[] args)
    {
        string s = "C# \n  Programming \r Language \t ";

        Console.WriteLine("WhiteSpaces = " + countWhitespaceCharacters(s));
    }
}


/*
run:
   
WhiteSpaces = 10
   
*/

 



answered Oct 19, 2024 by avibootz

Related questions

1 answer 129 views
1 answer 110 views
1 answer 123 views
1 answer 106 views
1 answer 89 views
1 answer 106 views
1 answer 78 views
...