5

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?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
kikx
  • 61
  • 1
  • 1
  • 3
  • Like Jan Doerrenhaus indicates in a comment, saying `s.Replace(" ", "");` as a statement by itself leads to the result being discarded. You need `s = s.Replace(" ", "");` instead, where the return value is assigned back to your variable `s`. Remeber that strings are immutable in C#. – Jeppe Stig Nielsen May 17 '13 at 12:36

7 Answers7

17

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).
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • 4
    Or maybe `"I am Bob".Length - "I am Bob".Count(Char.IsWhiteSpace)` which does a subtraction but doesn't need to create a lambda. No, I am probably micro-optimizing. – Jeppe Stig Nielsen May 17 '13 at 12:29
  • 3
    Great, maybe this comment will get +1 as well :-) ***If*** your string `"I am Bob"` might contain combining accents _or_ surrogate pairs (Unicode characters that need _two_ 16-bit values in UTF-16), then the interpretation of the count (or even `Length`) should be careful. – Jeppe Stig Nielsen May 17 '13 at 12:41
7

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

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
4

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
Jan Dörrenhaus
  • 6,581
  • 2
  • 34
  • 45
  • 1
    Good point he probably forgot to re-assign. I agree. Otherwise it would have worked for him. But there is no reason to have multiple `Replace` after each other like you have above. Once all spaces are replaced by `""`, there's no more spaces to replace in the calls that follow. – Jeppe Stig Nielsen May 17 '13 at 12:33
  • Wow, now I feel incredibly stupid... Exactly right, I didn't assign the new value so it just got lost. Made a local variable to hold the new string without spaces, works like a charm. THANK YOU! – kikx May 17 '13 at 18:31
1

A pretty simple way is to write an extension method that will do just that- count the characters without the white spaces. Here's the code:

public static class MyExtension
{
    public static int CharCountWithoutSpaces(this string str)
    {
        string[] arr = str.Split(' ');
        string allChars = "";
        foreach (string s in arr)
        {
            allChars += s;
        }
        int length = allChars.Length;
        return length;
    }
}

To execute, simply call the method on the string:

string yourString = "I am Bob";
        int count = yourString.CharCountWithoutSpaces();
        Console.WriteLine(count); //=6

Alternatively, you can split the string an way you want if you don't want to include say, periods or commas:

string[] arr = str.Split('.');

or:

string[] arr = str.Split(',');
MirrorEyes
  • 57
  • 4
0

this is fastest way:

var spaceCount = 0;
for (var i 0; i < @string.Lenght; i++)
{
    if (@string[i]==" ") spaceCount++;
}
var res = @string.Lenght-spaceCount;
burning_LEGION
  • 13,246
  • 8
  • 40
  • 52
  • How fast is `string.Lenght` (or even `string.Length`)? Would it be better to assign it to a variable before the loop and then use that variable twice? And why all the `@` characters in `@string`? – AdrianHHH May 17 '13 at 12:26
  • @AdrianHHH this is template to create method therefore i don't optimize it, read about c# to know what is `@` – burning_LEGION May 17 '13 at 12:33
0

Your problem is probably related to Replace() method not actually changing the string, rather returning the replaced value;

string withSpaces = "I am Bob";
string withoutSpaces = withSpaces.Replace(" ","");
Console.WriteLine(withSpaces);
Console.WriteLine(withoutSpaces);
Console.WriteLine(withSpaces.Length);
Console.WriteLine(withoutSpaces.Length);

//output
//I am Bob
//IamBob
//8
//6
0

You can use a combination of Length and Count functions on the string object. Here is a simple example.

    string sText = "This is great  text";
    int nSpaces = sText.Length - sText.Count(Char.IsWhiteSpace);

This will count single or multiple (consistent) spaces accurately.

Hope it helps.