简体   繁体   English

如何在c#中将字符串截断或填充为固定长度

[英]How to truncate or pad a string to a fixed length in c#

Is there a one-liner way of setting a string to a fixed length (in C#), either by truncating it or padding it with spaces ( ' ' ).是否有一种将string设置为固定长度的单行方式(在 C# 中),通过截断它或用空格( ' '填充它。

For example:例如:

string s1 = "abcdef";
string s2 = "abc";

after setting both to length 5 , we should have:将两者都设置为长度5 ,我们应该有:

"abcde"
"abc  "

All you need is PadRight followed by Substring (providing that source is not null ):您只需要PadRight后跟SubstringPadRightsource不为null ):

string source = ...
int length = 5;

string result = source.PadRight(length).Substring(0, length);

In case source can be null :如果source可以null

string result = source == null 
  ? new string(' ', length) 
  : source.PadRight(length).Substring(0, length);
private string fixedLength(string input, int length){
    if(input.Length > length)
        return input.Substring(0,length);
    else
        return input.PadRight(length, ' ');
}

(This answer previously contained incorrect code, as referenced in the comments.) (此答案以前包含错误的代码,如评论中所述。)

A custom one-liner would be str.Length > 5 ? str.Substring(0,5) : str.PadRight(5);定制的str.Length > 5 ? str.Substring(0,5) : str.PadRight(5);将是str.Length > 5 ? str.Substring(0,5) : str.PadRight(5); str.Length > 5 ? str.Substring(0,5) : str.PadRight(5); . .

Have you tried s1.PadLeft(5);你试过 s1.PadLeft(5);

you can also specify the character for padding if you want something else than spaces如果您想要除空格以外的其他内容,您还可以指定填充字符

s1.PadLeft(6, '.');

Would give you: "abcdef."会给你:“abcdef”。

to do both:两者都做:

var s1 = "1234567890";
var s2 = s1.SubString(5).PadLeft(5);

I would use the @waka answer, but as an extension method and null verification, like this:我会使用@waka 答案,但作为扩展方法和空验证,如下所示:

    public static string FixedLength(this string value, int totalWidth, char paddingChar)
    {
        if (value is null)
            return new string(paddingChar, totalWidth);

        if (value.Length > totalWidth)
            return value.Substring(0, totalWidth);
        else
            return value.PadRight(totalWidth, paddingChar);
    }

你可以使用string.PadLeftstring.PadRight https://msdn.microsoft.com/en-us/library/66f6d830(v=vs.110).aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM