C# 用于创建包含多个空白字符的字符串的 " " 的替代方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1716230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 20:12:54  来源:igfitidea点击:

Alternatives to " " for creating strings containing multiple whitespace characters

c#stringspaces

提问by Jamie Dixon

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

我想知道在 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.

我目前拥有tabs += new String(" ");并且我不禁觉得这有点让人想起使用""而不是String.Empty.

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

我可以用什么来创建不是的空间" "

采纳答案by dtb

You can write

你可以写

" "

instead of

代替

new String(' ')

Does that help?

这有帮助吗?



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

根据您的操作,您可能需要查看接受字符和“重复”计数的StringBuilder.Append重载:

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

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

或进入从一个“重复”计数的字符构造一个字符串的string构造函数:

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


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

这是一个企业 OO 解决方案,可满足您所有的空间生成需求:

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

回答by Austin Salonen

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

根据这在您的代码中的流行程度,StringBuilder 方式可能更好。

StringBuilder tabs = new StringBuilder();
...

tabs.Append(" ");

You can mix in the constant too...

你也可以混入常量......

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

tabs.Append(SPACE);

回答by TStamper

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);

回答by Mark Dickinson

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.

不过这本身就很糟糕。

回答by Gabe Moothart

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

没有理由这样做。在其他条件相同的情况下,较小的代码是更好的代码String.Emptynew String(' ')传达同样的事情,""而且" ",他们只是需要更多的字符来做到这一点。

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

试图让它“更面向对象”只会增加字符而没有任何好处。面向对象本身并不是目的。

回答by avid

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

如果语言允许,您可以将扩展属性添加到类型为 Space 的 String 中,例如:

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.

但那是不可能的。我认为如果它是可本地化的东西,最好将空间保留在属性内,但我认为空间在所有语言中都是通用的。

回答by Jon Skeet

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.

在我的实际代码中,我正在执行 new String(' ',numberOfSpaces) 所以我可能仍然需要使用新的 String 部分。

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

...到目前为止,其他答案实际上毫无用处:(

You couldwrite:

可以写:

const char Space = ' ';

then use

然后使用

new string(Space, numberOfSpaces)

but I don't see any benefit of that over

但我没有看到任何好处

new string(' ', numberOfSpaces)

回答by corymathews

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

我认为您采用 OO 方式走得太远了.. 一个简单的空间添加不需要整个类。

tabs += new String(' ');

or

或者

tabs += " ";

is just fine.

很好。

回答by Christian Hayter

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 tabssuggests to me that you are trying to roll your own column alignment code. String.Formatsupports that directly, e.g.

更“OO”的方法是找到一种更简单的方法来解决更大的业务问题。例如,您有一个名为变量的事实tabs向我表明您正在尝试推出自己的列对齐代码。String.Format直接支持,例如

// 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));
}

回答by Matt Ellen

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

"\t"我认为您可以使用给您一个制表符。这可能会使间距更清晰。