Alternatives to " " for creating strings containing multiple whitespace characters
Asked Answered
B

13

28

I'm wondering if there's a more OO way of creating spaces in C#.

Literally Space Code!

I currently have tabs += new String(" "); and I can't help but feel that this is somewhat reminiscent of using "" instead of String.Empty.

What can I use to create spaces that isn't " "?

Bothy answered 11/11, 2009 at 16:12 Comment(11)
And there's nothing wrong with "" rather than string.Empty either.Discredit
I don't think there's anything "wrong" as such. I'm just wondering if there's another way to do it that's perhaps more...OO...dare i say.Bothy
There's nothing inherently OO or non-OO about using " " or a named constant.Uncloak
Part of the reason for this question is that I've recently joined a new team. The lead architect pulled me up on a few occasions for using "" instead of String.Empty and I wanted to know if there was another way of doing spaces before he gets chance to pull me up on that. Now I know i'll stick with using String(" ",numOfSpaces). Thanks everyone for your replies!Bothy
(insert mandatory 'use StringBuilder' remark here)Tinderbox
@Luke: I believe that String.Empty is a fixed reference while using "" actually creates a new object that will then have to be GCed, but now I can't remember where I read that.Snooze
@Joe. In fact all instances of "" in the source code will point to the same string, due to interning. According to Tony The Pony at least. yoda.arachsys.com/csharp/strings.htmlMidvictorian
@Joe, @MarkJ: Also take a look at this article and its comments: blogs.msdn.com/ericlippert/archive/2009/09/28/…Discredit
Apologies for changing the title, but the new one might make it easier to search for in future.Hadwin
I wish it was built into .net framework string.Space(); string.Space(int repeat);Scleroma
StringBuilder.Insert and StringBuilder.Append allow you to create any number spaces, e.g. sb.Insert(0, " ", 20) will insert 20 spaces to the start of your sb (StringBuilder) object.Upstart
A
49

You can write

" "

instead of

new String(' ')

Does that help?


Depending on what you do, you might want to look into the StringBuilder.Append overload that accepts a character and a 'repeat' count:

var tabs = new StringBuilder();
tabs.Append(' ', 8);

or into the string constructor that constructs a string from a character a 'repeat' count:

var tabs = new string(' ', 8);

Here's an enterprisey OO solution to satisfy all your space generation needs:

public abstract class SpaceFactory
{
    public static readonly SpaceFactory Space = new SpaceFactoryImpl();

    public static readonly SpaceFactory ZeroWidth = new ZeroWidthFactoryImpl();

    protected SpaceFactory { }

    public abstract char GetSpace();

    public virtual string GetSpaces(int count)
    {
        return new string(this.GetSpace(), count);
    }

    private class SpaceFactoryImpl : SpaceFactory
    {
        public override char GetSpace()
        {
            return '\u0020';
        }
    }

    private class ZeroWidthFactoryImpl : SpaceFactory
    {
        public override char GetSpace()
        {
            return '\u200B';
        }
    }
}
Aube answered 11/11, 2009 at 16:16 Comment(5)
In my actual code I'm doing new String(' ',numberOfSpaces) so I probably need to still use the new String part.Bothy
@Jamie: It would have been useful to say that to start with, as it makes basically all the existing answers invalid.Uncloak
Yeah appologies for that. I think other people might have this question at some point, and those people might not be specifying the number of spaces so I think these answers will be useful for them.Bothy
Thanks dtb. I had to accept this one, not only because you answered the question at the top, but also for your use of the terms "SpaceFactory" and "enterprisey".Bothy
@Aube I changed the title as there is an almost identical question this evening, but I tried to leave the original reference to SpaceCode in to preserve context for this very amusing answer. To quote your avatar, "Oh No!"Hadwin
U
15

Now that you've clarified in comments:

In my actual code I'm doing new String(' ',numberOfSpaces) so I probably need to still use the new String part.

... the other answers so far are effectively useless :(

You could write:

const char Space = ' ';

then use

new string(Space, numberOfSpaces)

but I don't see any benefit of that over

new string(' ', numberOfSpaces)
Uncloak answered 11/11, 2009 at 16:24 Comment(0)
P
8

if the number of spaces would be changing then you could do something like this:

public static string Space(int count)
{
    return "".PadLeft(count);
}

Space(2);
Philomel answered 11/11, 2009 at 16:18 Comment(2)
Nice, but I'd use String.Empty to satisfy his dislike of strings in code!Cyndie
Or use the string constructor that takes a character count instead: return new string(' ', count);Discredit
J
6

There is no reason to do this. All else being equal, smaller code is better code. String.Empty and new String(' ') communicate the same thing as "" and " ", they just take more characters to do it.

Trying to make it 'more OO' just adds characters for no benefit. Object-Orientation is not an end in itself.

Jigaboo answered 11/11, 2009 at 16:20 Comment(0)
F
3

Depending on how prevalent this is in your code, the StringBuilder way may be better.

StringBuilder tabs = new StringBuilder();
...

tabs.Append(" ");

You can mix in the constant too...

StringBuilder tabs = new StringBuilder();
const string SPACE = " ";
...

tabs.Append(SPACE);
Fichu answered 11/11, 2009 at 16:17 Comment(0)
S
3

Extend string to give you a method to add space

public static string AddSpace(this String text, int size)
{
   return text + new string(' ', size)
}

Awful in it's own right though.

Samurai answered 11/11, 2009 at 16:19 Comment(3)
+1 - extension methods seem to be in line with the OP's style here. Note you can replace the body of this function with return new String(' ', count); as this overloaded constructor does exactly what you've done :)Interpretive
Even though an extension method may be desired, there's no need to use repeated string concatenation like this. "return text + new string(' ', size)" would be more appropriate IMO. (Having changed the first parameter from the keyword string to text...)Uncloak
Thanks John and Jon (sorry Tony). Yes that feels much better, being a web bod I rarely want to have two spaces next to each other anyway, just thought I'd add my two pence worth.Samurai
E
2

The more "OO" way would be to find a simpler way of solving your larger business problem. For example, the fact that you have a variable named tabs suggests to me that you are trying to roll your own column alignment code. String.Format supports that directly, e.g.

// Left-align name and status, right-align amount (formatted as currency).
writer.WriteLine("Name                 Status         Amount");
writer.WriteLine("-------------------- ---------- ----------");
foreach(var item in items) {
    writer.WriteLine(string.Format("{0,-20} {1,-10} {2,10:C}", item.Name, item.Status, item.Amount));
}
Emmanuel answered 11/11, 2009 at 16:44 Comment(1)
Thanks Christian. The larger problem i'm solving is that I've got an IEnumerable of objects with an Id and ParentId. I'm outputting the contents of these objects to CSV format for data export and need to show the relationship between the objects. On the screen they're shown as a Tree grid and for export I'm spacing them to show the relationship.Bothy
P
1

If the language allowed for it you could add an extension property to the type String which was Space, something like:

public static class StringExt
{
    public static char Space(this String s)
    {
        get {
            return ' ';
        }
    }
}

but that isn't possible. I think it would be better to keep the space inside the property if it was a localizable thingy, but I think spaces are universal across all languages.

Philender answered 11/11, 2009 at 16:20 Comment(0)
B
1

I think you are taking OO way to far.. A simple addition of a space does not need an entire class.

tabs += new String(' ');

or

tabs += " ";

is just fine.

Belovo answered 11/11, 2009 at 16:31 Comment(0)
E
0

You could use "\t", I think, to give you a tab character. That might make the spaceing more clear.

Erlene answered 11/11, 2009 at 17:19 Comment(0)
U
0

StringBuilder.Insert and StringBuilder.Append allow you to create any number spaces, e.g. sb.Insert(0, " ", 20) will insert 20 spaces to the start of your sb (StringBuilder) object.

Upstart answered 24/4, 2014 at 7:42 Comment(0)
C
0

You may create class extensions.

public static class StringExtensions
    {
        public static string GetSpace(this String)
        {
           return " ";
        }
    }

and you can call this.

String.GetSPace();
Concupiscence answered 26/9, 2018 at 5:24 Comment(0)
S
0

I tend to use string.Empty.PadLeft(8) for example

Shericesheridan answered 6/7, 2022 at 7:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.