Michal_LFC
Michal_LFC

Reputation: 599

Count words and spaces in string C#

I want to count words and spaces in my string. String looks like this:

Command do something ptuf(123) and bo(1).ctq[5] v:0,

I have something like this so far

int count = 0;
string mystring = "Command do something ptuf(123) and bo(1).ctq[5] v:0,";
foreach(char c in mystring) 
{
if(char.IsLetter(c)) 
  {
     count++;
  }
}

What should I do to count spaces also?

Upvotes: 14

Views: 65726

Answers (10)

Pawan Paul Jay
Pawan Paul Jay

Reputation: 1

How about indirectly?

int countl = 0, countt = 0, count = 0;

foreach(char c in str) 
{
    countt++;
    if (char.IsLetter(c)) 
    {
        countl++;
    }
}
count = countt - countl;
Console.WriteLine("No. of spaces are: "+count);

Upvotes: 0

user9590032
user9590032

Reputation:

if you need whitespace count only try this.

string myString="I Love Programming";
var strArray=myString.Split(new char[] { ' ' });
int countSpace=strArray.Length-1;

Upvotes: 0

Karthick
Karthick

Reputation: 1

using namespace;
namespace Application;
class classname
{
    static void Main(string[] args)
    {
        int count;
        string name = "I am the student";
        count = name.Split(' ').Length;
        Console.WriteLine("The count is " +count);
        Console.ReadLine();
    }
}

Upvotes: 0

Gray
Gray

Reputation: 7130

Here's a method using regex. Just something else to consider. It is better if you have long strings with lots of different types of whitespace. Similar to Microsoft Word's WordCount.

var str = "Command do something ptuf(123) and bo(1).ctq[5] v:0,";
int count = Regex.Matches(str, @"[\S]+").Count; // count is 7

For comparison,

var str = "Command     do    something     ptuf(123) and bo(1).ctq[5] v:0,";

str.Count(char.IsWhiteSpace) is 17, while the regex count is still 7.

Upvotes: 1

TTT
TTT

Reputation: 1885

This will take into account:

  • Strings starting or ending with a space.
  • Double/triple/... spaces.

Assuming that the only word seperators are spaces and that your string is not null.

private static int CountWords(string S)
{
    if (S.Length == 0)
        return 0;

    S = S.Trim();
    while (S.Contains("  "))
        S = S.Replace("  "," ");
    return S.Split(' ').Length;
}

Note: the while loop can also be done with a regex: How do I replace multiple spaces with a single space in C#?

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460048

int countSpaces = mystring.Count(Char.IsWhiteSpace); // 6
int countWords = mystring.Split().Length; // 7

Note that both use Char.IsWhiteSpace which assumes other characters than " " as white-space(like newline). Have a look at the remarks section to see which exactly .

Upvotes: 38

Brad Christie
Brad Christie

Reputation: 101594

In addition to Tim's entry, in case you have padding on either side, or multiple spaces beside each other:

Int32 words = somestring.Split(           // your string
    new[]{ ' ' },                         // break apart by spaces
    StringSplitOptions.RemoveEmptyEntries // remove empties (double spaces)
).Length;                                 // number of "words" remaining

Upvotes: 0

Daniel Möller
Daniel Möller

Reputation: 86600

I've got some ready code to get a list of words in a string: (extension methods, must be in a static class)

    /// <summary>
    /// Gets a list of words in the text. A word is any string sequence between two separators.
    /// No word is added if separators are consecutive (would mean zero length words).
    /// </summary>
    public static List<string> GetWords(this string Text, char WordSeparator)
    {
        List<int> SeparatorIndices = Text.IndicesOf(WordSeparator.ToString(), true);

        int LastIndexNext = 0;


        List<string> Result = new List<string>();
        foreach (int index in SeparatorIndices)
        {
            int WordLen = index - LastIndexNext;
            if (WordLen > 0)
            {
                Result.Add(Text.Substring(LastIndexNext, WordLen));
            }
            LastIndexNext = index + 1;
        }

        return Result;
    }

    /// <summary>
    /// returns all indices of the occurrences of a passed string in this string.
    /// </summary>
    public static List<int> IndicesOf(this string Text, string ToFind, bool IgnoreCase)
    {
        int Index = -1;
        List<int> Result = new List<int>();

        string T, F;

        if (IgnoreCase)
        {
            T = Text.ToUpperInvariant();
            F = ToFind.ToUpperInvariant();
        }
        else
        {
            T = Text;
            F = ToFind;
        }


        do
        {
            Index = T.IndexOf(F, Index + 1);
            Result.Add(Index);
        }
        while (Index != -1);

        Result.RemoveAt(Result.Count - 1);

        return Result;
    }


    /// <summary>
    /// Implemented - returns all the strings in uppercase invariant.
    /// </summary>
    public static string[] ToUpperAll(this string[] Strings)
    {
        string[] Result = new string[Strings.Length];
        Strings.ForEachIndex(i => Result[i] = Strings[i].ToUpperInvariant());
        return Result;
    }

Upvotes: 0

Jonesopolis
Jonesopolis

Reputation: 25370

if you want to count spaces you can use LINQ :

int count = mystring.Count(s => s == ' ');

Upvotes: 2

asafrob
asafrob

Reputation: 1858

you can use string.Split with a space http://msdn.microsoft.com/en-us/library/system.string.split.aspx

When you get a string array the number of elements is the number of words, and the number of spaces is the number of words -1

Upvotes: 2

Related Questions