Quick actions

cmd+k|ctrl+k

Navigation

Languages

count number of words in string

Snippet info

Language

Csharp

Visibility

public

Author

dhaval-90

Created

2022-05-04T09:45:05.403111Z

Updated

2022-05-04T09:50:41.904158Z

using System;
using System.Collections.Generic;
using System.Linq;

class MainClass {
    static void Main() {
        Console.WriteLine("Hello World!");
        string str = "Hello World    This is Dhaval";
        Console.WriteLine(WordCount(str));
        string[] array = str.Split(" ");
        Console.WriteLine(array.Length);
        Console.WriteLine(str.Split(" ").Length);
    }
    
    public static int WordCount(string str)
{        
    int num=0;
    bool wasInaWord=true;;

    if (string.IsNullOrEmpty(str))
    {
        return num;
    }

    for (int i=0;i< str.Length;i++)
    {
        if (i!=0)
        {
            if (str[i]==' ' && str[i-1]!=' ')
            {
                num++;
                wasInaWord=false;
            }
        } 
            if (str[i]!=' ')
            {
                wasInaWord=true;                
            }
    }
    if (wasInaWord)
    {
        num++;
    }
    return num;
}
}
INFO