在 C# 中为字符串添加空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15851730/
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-10 18:09:13  来源:igfitidea点击:

Adding whitespaces to a string in C#

c#string

提问by user1765862

I'm getting a stringas a parameter.

我得到一个string作为参数。

Every string should take 30 characters and after I check its length I want to add whitespaces to the end of the string.
E.g. if the passed string is 25 characters long, I want to add 5 more whitespaces.

每个字符串都应包含 30 个字符,在检查其长度后,我想在字符串的末尾添加空格。
例如,如果传递的字符串长度为 25 个字符,我想再添加 5 个空格。

The question is, how do I add whitespaces to a string?

问题是,如何向字符串添加空格?

采纳答案by RedFilter

You can use String.PadRightfor this.

您可以为此使用String.PadRight

Returns a new string that left-aligns the characters in this string by padding them with spaces on the right, for a specified total length.

返回一个新字符串,该字符串左对齐此字符串中的字符,通过在右侧填充空格来实现指定的总长度。

For example:

例如:

string paddedParam = param.PadRight(30);

回答by Daniel Imms

Use String.PadRightwhich will space out a string so it is as long as the intprovided.

使用String.PadRightwhich 将隔开一个字符串,使其与所int提供的一样长。

var str = "hello world";
var padded = str.PadRight(30);
// padded = "hello world                   "

回答by Soner G?nül

You can use String.PadRightmethod for this;

您可以String.PadRight为此使用方法;

Returns a new string of a specified length in which the end of the current string is padded with spaces or with a specified Unicode character.

返回一个指定长度的新字符串,其中当前字符串的末尾用空格或指定的 Unicode 字符填充。

string s = "cat".PadRight(10);
string s2 = "poodle".PadRight(10);

Console.Write(s);
Console.WriteLine("feline");
Console.Write(s2);
Console.WriteLine("canine");

Output will be;

输出将是;

cat       feline
poodle    canine

Here is a DEMO.

这是一个DEMO.

PadRight adds spaces to the right of strings. It makes text easier to read or store in databases. Padding a string adds whitespace or other characters to the beginning or end. PadRight supports any character for padding, not just a space.

PadRight 在字符串的右侧添加空格。它使文本更易于阅读或存储在数据库中。填充字符串会在开头或结尾添加空格或其他字符。PadRight 支持用于填充的任何字符,而不仅仅是空格。

回答by Girish

you can use Padding in C#

你可以在 C# 中使用 Padding

eg

例如

  string s = "Example";
  s=s.PadRight(30);

I hope It should be resolve your Problem.

我希望它应该可以解决您的问题。