简体   繁体   English

如果字符串的长度小于15,如何获取字符串的前15个字符或更少的字符?

[英]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. 但是,如果字符串的长度小于15,则失败。 Is there a standard way to do this in one statement that would work even if the string length is less than 15. 有没有一种标准的方法可以在一个语句中做到这一点,即使该字符串的长度小于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 : 否则,您可以使用扩展方法Take与string.Join一起使用,如下所示:

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

The .Take will take the specified items if present. .Take将接受指定的项目(如果存在)。 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: 我实际上创建了一个名为Truncate的扩展方法,该方法经常用于此目的-主要是为了防止插入或更新比数据库大的字符串:

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

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

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