0

I'm new to coding and I want to make a program which counts the characters in a text file, but I want it to just count the letters and other symbols but the spaces in-between each word is getting recognized as a character, is there a way to make it so it doesn't count spaces as a character?

My code so far:

        label2.Text = richTextBox1.Text.Length.ToString();
corzan
  • 21
  • 4
  • 1
    You can look into using `.Count()` on the string and use the lambda expression to filter out space chars – li223 Apr 26 '20 at 15:09
  • duplicate of: https://stackoverflow.com/questions/16608691/length-of-string-without-spaces-c – Yonatan Nethanel Apr 26 '20 at 15:12
  • Does this answer your question? [Length of string WITHOUT spaces (C#)](https://stackoverflow.com/questions/16608691/length-of-string-without-spaces-c) – Edward Apr 26 '20 at 16:30

3 Answers3

0

This code has been taken from Yonatan's link : Length of string WITHOUT space

label2.Text = richTextBox1.Text.Count(c => !Char.IsWhiteSpace(c)).ToString();
D J
  • 845
  • 1
  • 13
  • 27
  • @corzan: From next time, pls google your problem or search it on StackOverflow and prevent asking questions that are previously asked. – D J Apr 26 '20 at 16:32
  • I tried using your solution but it doesn't work since I can't convert a int to string. – corzan Apr 26 '20 at 16:50
  • @corzan: Pls try my updated code and revert for any errors.(Wish there are none :)) – D J Apr 27 '20 at 06:27
0

You can use multiple ways

1) By Regular Expression

Regex.Replace(richTextBox1.Text, @"\s+", "").Length

2) Using LINQ

label2.Text  = richTextBox1.Text.Where(s => s != ' ').ToArray<char>().Count()
0

This works just fine for me:

label2.Text = richTextBox1.Text.Replace(" ", "").Length.ToString();

DotNetFiddle

Momoro
  • 599
  • 4
  • 23