Count words and spaces in a C # line

I want to count the words and spaces in my line. The line 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?

+8
c # visual-studio-2010 winforms
source share
8 answers
 int countSpaces = mystring.Count(Char.IsWhiteSpace); // 6 int countWords = mystring.Split().Length; // 7 

Note that both use Char.IsWhiteSpace , which accepts characters other than " " as white space (e.g. newline ). Take a look at the comments section to find out exactly what.

+27
source share

you can use string.Split with 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

+2
source share

This will take into account:

  • Lines beginning or ending with a space.
  • Double / triple / ... spaces.

Assuming that the only word separator is spaces, and that your line is non-zero.

 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: while loop can also be done using regular expression: How to replace multiple spaces with one place in C #?

+1
source share

if you want to count spaces, you can use LINQ:

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

I have 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; } 
0
source share

In addition to Tim's entry, if you have an addition on both sides or several places next to each other:

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

The method using regex is used here. Just something else to consider. It is better if you have long lines with a lot of different types of spaces. Like Microsoft Word 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, and the number of regular expressions is 7.

0
source share
 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(); } } 
0
source share

All Articles