我想为String类编写一个扩展方法,以便如果输入字符串比提供的长度N长,则只显示前N个字符。
这是它的样子:
public static string TruncateLongString(this string str, int maxLength)
{
if (str.Length <= maxLength)
return str;
else
//return the first maxLength characters
}
什么字符串.*()方法我可以使用只得到str的前N个字符?
public static string TruncateLongString(this string str, int maxLength)
{
if (string.IsNullOrEmpty(str)) return str;
return str.Substring(0, Math.Min(str.Length, maxLength));
}
在c# 8或更高版本中,也可以使用Range使其更简洁:
public static string TruncateLongString(this string str, int maxLength)
{
return str?[0..Math.Min(str.Length, maxLength)];
}
可以使用表达式体进一步简化:
public static string TruncateLongString(this string str, int maxLength) =>
str?[0..Math.Min(str.Length, maxLength)];
注意空条件操作符(?)用于处理str为空的情况。这取代了显式空检查的需要。
每当我必须在c#中进行字符串操作时,我就会想念Visual Basic中的Left和Right函数,它们比Substring使用起来简单得多。
所以在我的大多数c#项目中,我为它们创建了扩展方法:
public static class StringExtensions
{
public static string Left(this string str, int length)
{
return str.Substring(0, Math.Min(length, str.Length));
}
public static string Right(this string str, int length)
{
return str.Substring(str.Length - Math.Min(length, str.Length));
}
}
注意:
的数学。Min部分的存在是因为当输入字符串的长度小于所请求的长度时,Substring会抛出一个argumentoutofranceexception,正如在前面的回答下的一些评论中已经提到的那样。
用法:
string longString = "Long String";
// returns "Long";
string left1 = longString.Left(4);
// returns "Long String";
string left2 = longString.Left(100);
The .NET Substring method is fraught with peril. I developed extension methods that handle a wide variety of scenarios. The nice thing is it preserves the original behavior, but when you add an additional "true" parameter, it then resorts to the extension method to handle the exception, and returns the most logical values, based on the index and length. For example, if length is negative, and counts backward. You can look at the test results with wide variety of values on the fiddle at: https://dotnetfiddle.net/m1mSH9. This will give you a clear idea on how it resolves substrings.
我总是将这些方法添加到我所有的项目中,并且从来不必担心代码破坏,因为某些东西发生了变化,索引无效。下面是代码。
public static String Substring(this String val, int startIndex, bool handleIndexException)
{
if (!handleIndexException)
{ //handleIndexException is false so call the base method
return val.Substring(startIndex);
}
if (string.IsNullOrEmpty(val))
{
return val;
}
return val.Substring(startIndex < 0 ? 0 : startIndex > (val.Length - 1) ? val.Length : startIndex);
}
public static String Substring(this String val, int startIndex, int length, bool handleIndexException)
{
if (!handleIndexException)
{ //handleIndexException is false so call the base method
return val.Substring(startIndex, length);
}
if (string.IsNullOrEmpty(val))
{
return val;
}
int newfrom, newlth, instrlength = val.Length;
if (length < 0) //length is negative
{
newfrom = startIndex + length;
newlth = -1 * length;
}
else //length is positive
{
newfrom = startIndex;
newlth = length;
}
if (newfrom + newlth < 0 || newfrom > instrlength - 1)
{
return string.Empty;
}
if (newfrom < 0)
{
newlth = newfrom + newlth;
newfrom = 0;
}
return val.Substring(newfrom, Math.Min(newlth, instrlength - newfrom));
}
早在2010年5月,我就在http://jagdale.blogspot.com/2010/05/substring-extension-method-that-does.html上写了一篇博文
部分为了总结(不包括LINQ解决方案),这里有两个一行程序,解决了int maxLength允许负值的警告和空字符串的情况:
Substring方式(来自Paul Ruane的回答):
public static string Truncate(this string s, uint maxLength) =>
s?.Substring(0, Math.Min(s.Length, (int)maxLength));
移除方式(来自kbrimington的回答):
public static string Truncate(this string s, uint maxLength) =>
s?.Length > maxLength ? s.Remove((int)maxLength) : s;