问题描述
我这样一个问题,可能有一个简单的解决方案表示歉意,但奇怪的是,我无法找到一个简洁的API为这个问题。
I apologize for such a question that likely has a trivial solution, but strangely, I could not find a concise API for this problem.
从本质上讲,我想截断一个字符串,它的长度不大于给定的值长。我写一个数据库表,并希望确保我写的值满足列的数据类型的约束。
Essentially, I would like to truncate a string such that its length is not longer than a given value. I am writing to a database table and want to ensure that the values I write meet the constraint of the column's datatype.
例如,这将是很好,如果我能写:
For instance, it would be nice if I could write the following:
string NormalizeLength(string value, int maxLength)
{
return value.Substring(0, maxLength);
}
不幸的是,这引发了一个异常,因为最大长度
一般超过字符串值
的边界。当然,我可以写如下的类似功能,但我希望这样的事情已经存在。
Unfortunately, this raises an exception because maxLength
generally exceeds the boundaries of the string value
. Of course, I could write a function like the following, but I was hoping that something like this already exists.
string NormalizeLength(string value, int maxLength)
{
return value.Length <= maxLength ? value : value.Substring(0, maxLength);
}
哪里是难以捉摸的API,它执行这个任务?有一?
Where is the elusive API that performs this task? Is there one?
推荐答案
没有一个截断()
方法对串,很遗憾。你必须写这样的逻辑自己。你可以做什么,然而,这种包装在一个扩展方法,所以你不必到处复制它:
There isn't a Truncate()
method on string, unfortunately. You have to write this kind of logic yourself. What you can do, however, is wrap this in an extension method so you don't have to duplicate it everywhere:
public static class StringExt
{
public static string Truncate(this string value, int maxLength)
{
if (string.IsNullOrEmpty(value)) return value;
return value.Length <= maxLength ? value : value.Substring(0, maxLength);
}
}
现在我们可以这样写:
var someString = "...";
someString = someString.Truncate(2);
这篇关于我如何截断.NET字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!