简体   繁体   中英

How can I get the first 15 characters of a string or less if the string is less than 15 in length?

I tried using this:

 Note = phrase.English.Substring(0, 15);

But this fails if strings are less than 15 in length. Is there a standard way to do this in one statement that would work even if the string length is less than 15.

Make use of ternary operator:

Note = phrase.English.Length > 15? phrase.English.Substring(0, 15):phrase.English;

Or else you can use the extension method Take along with string.Join as like the following :

string  Note = String.Join("",phrase.English.Take(15));

The .Take will take the specified items if present. Here you can check out a working example

I actually created an extension method called Truncate, which I use frequently for this purpose -- mostly to prevent strings larger than the database can handle from being inserted or updated:

    public static string Truncate(this string value, int maxLength)
    {
        if (string.IsNullOrEmpty(value)) return value;
        return value.Length <= maxLength ? value : value.Substring(0, maxLength);
    }

Usage:

string s = "Hello World";
string t = s.Truncate(5);
string one = "12345678901234567890";
string other = string.Join("",one .Take(15));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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