Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Length of string WITHOUT spaces (C#)

Tags:

string

c#

spaces

Quick little question...

I need to count the length of a string, but WITHOUT the spaces inside of it. E.g. for a string like "I am Bob", string.Length would return 8 (6 letters + 2 spaces).

I need a method, or something, to give me the length (or number of) just the letters (6 in the case of "I am Bob")

I have tried the following

s.Replace (" ", "");
s.Replace (" ", null);
s.Replace (" ", string.empty);

to try and get "IamBob", which I did, but it didn't solve my problem because it still counted "" as a character.

Any help?

like image 871
kikx Avatar asked May 17 '13 12:05

kikx


3 Answers

This returns the number of non-whitespace characters:

"I am Bob".Count(c => !Char.IsWhiteSpace(c));

Demo

Char.IsWhiteSpace:

White space characters are the following Unicode characters:

  • Members of the SpaceSeparator category, which includes the characters SPACE (U+0020), OGHAM SPACE MARK (U+1680), MONGOLIAN VOWEL SEPARATOR (U+180E), EN QUAD (U+2000), EM QUAD (U+2001), EN SPACE (U+2002), EM SPACE (U+2003), THREE-PER-EM SPACE (U+2004), FOUR-PER-EM SPACE (U+2005), SIX-PER-EM SPACE (U+2006), FIGURE SPACE (U+2007), PUNCTUATION SPACE (U+2008), THIN SPACE (U+2009), HAIR SPACE (U+200A), NARROW NO-BREAK SPACE (U+202F), MEDIUM MATHEMATICAL SPACE (U+205F), and IDEOGRAPHIC SPACE (U+3000).
  • Members of the LineSeparator category, which consists solely of the LINE SEPARATOR character (U+2028).
  • Members of the ParagraphSeparator category, which consists solely of the PARAGRAPH SEPARATOR character (U+2029).
  • The characters CHARACTER TABULATION (U+0009), LINE FEED (U+000A), LINE TABULATION (U+000B), FORM FEED (U+000C), CARRIAGE RETURN (U+000D), NEXT LINE (U+0085), and NO-BREAK SPACE (U+00A0).
like image 118
Tim Schmelter Avatar answered Oct 28 '22 10:10

Tim Schmelter


No. It doesn't.

string s = "I am Bob";
Console.WriteLine(s.Replace(" ", "").Length); // 6
Console.WriteLine(s.Replace(" ", null).Length); //6
Console.WriteLine(s.Replace(" ", string.Empty).Length); //6

Here is a DEMO.

But what are whitespace characters?

http://en.wikipedia.org/wiki/Whitespace_character

whitespace characters

like image 7
Soner Gönül Avatar answered Oct 28 '22 10:10

Soner Gönül


You probably forgot to reassign the result of Replace. Try this:

string s = "I am bob";
Console.WriteLine(s.Length); // 8
s = s.Replace(" ", "");
Console.WriteLine(s.Length); // 6
like image 4
Jan Dörrenhaus Avatar answered Oct 28 '22 10:10

Jan Dörrenhaus