C#: Limit the length of a string? [duplicate]

2019-01-11 09:12发布

This question already has an answer here:

I was just simply wondering how I could limit the length of a string in C#.

string foo = "1234567890";

Say we have that. How can I limit foo to say, 5 characters?

11条回答
We Are One
2楼-- · 2019-01-11 09:34

Use Remove()...

string foo = "1234567890";
int trimLength = 5;

if (foo.Length > trimLength) foo = foo.Remove(trimLength);

// foo is now "12345"
查看更多
【Aperson】
3楼-- · 2019-01-11 09:35

If this is in a class property you could do it in the setter:

public class FooClass
{
   private string foo;
   public string Foo
   {
     get { return foo; }
     set
     {
       if(!string.IsNullOrEmpty(value) && value.Length>5)
       {
            foo=value.Substring(0,5);
       }
       else
            foo=value;
     }
   }
}
查看更多
Evening l夕情丶
4楼-- · 2019-01-11 09:36

Strings in C# are immutable and in some sense it means that they are fixed-size.
However you cannot constrain a string variable to only accept n-character strings. If you define a string variable, it can be assigned any string. If truncating strings (or throwing errors) is essential part of your business logic, consider doing so in your specific class' property setters (that's what Jon suggested, and it's the most natural way of creating constraints on values in .NET).

If you just want to make sure isn't too long (e.g. when passing it as a parameter to some legacy code), truncate it manually:

const int MaxLength = 5;


var name = "Christopher";
if (name.Length > MaxLength)
    name = name.Substring(0, MaxLength); // name = "Chris"
查看更多
孤傲高冷的网名
5楼-- · 2019-01-11 09:36

string shortFoo = foo.Length > 5 ? foo.Substring(0, 5) : foo;

Note that you can't just use foo.Substring(0, 5) by itself because it will throw an error when foo is less than 5 characters.

查看更多
萌系小妹纸
6楼-- · 2019-01-11 09:37

You can avoid the if statement if you pad it out to the length you want to limit it to.

string name1 = "Christopher";
string name2 = "Jay";
int maxLength = 5;

name1 = name1.PadRight(maxLength).Substring(0, maxLength);
name2 = name2.PadRight(maxLength).Substring(0, maxLength);

name1 will have Chris

name2 will have Jay

No if statement needed to check the length before you use substring

查看更多
爷、活的狠高调
7楼-- · 2019-01-11 09:38

You can try like this:

var x= str== null 
        ? string.Empty 
        : str.Substring(0, Math.Min(5, str.Length));
查看更多
登录 后发表回答