Alternatives to “ ” for creating strings containing multiple whitespace characters

后端 未结 12 1389
粉色の甜心
粉色の甜心 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:26

    You may create class extensions.

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

    and you can call this.

    String.GetSPace();
    
    0 讨论(0)
  • 2020-12-09 16:27

    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.

    0 讨论(0)
  • 2020-12-09 16:28

    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);
    
    0 讨论(0)
  • 2020-12-09 16:30

    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.

    0 讨论(0)
  • 2020-12-09 16:31

    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)
    
    0 讨论(0)
  • 2020-12-09 16:31

    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.

    0 讨论(0)
提交回复
热议问题