Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

c# - Alternatives to " " for creating strings containing multiple whitespace characters

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 " "?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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';
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...