Alternatives to “ ” for creating strings containing multiple whitespace characters

后端 未结 12 1399
粉色の甜心
粉色の甜心 2020-12-09 15:30

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\'

12条回答
  •  南方客
    南方客 (楼主)
    2020-12-09 16:05

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

提交回复
热议问题