C# Substring() 的问题 - ArgumentOutOfRangeException
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2021498/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Problem with Substring() - ArgumentOutOfRangeException
提问by Ivan Stoyanov
I have a repeater that displays data from my Projects table. There are projectId, name and description. I use Substring(1, 240) on description. But sometimes the string is shorter than 240, so I get ArgumentOutOfRangeException. Can you tell me how to display the whole text if I get the exception. This is my code.
我有一个显示项目表中数据的中继器。有 projectId、name 和 description。我在描述中使用 Substring(1, 240) 。但有时字符串比 240 短,所以我得到 ArgumentOutOfRangeException。如果出现异常,你能告诉我如何显示整个文本吗?这是我的代码。
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:Panel ID="pnlDisplayProjects" runat="server" Visible="true">
<center><h2><b>Проекти</b></h2></center>
<asp:Repeater ID="rptrProjects" runat="server">
<HeaderTemplate>
<table border="1" cellpadding="2" cellspacing="2" align="center" width="80%" style="background-color:#F7F6F3;">
</HeaderTemplate>
<ItemTemplate>
<tr>
<td align="left" style="width:40px">
<asp:Label ID="LblProjectId" runat="server" Text='<%# Eval("ProjectID") %>' />
</td>
<td align="center">
<asp:Label ID="LblName" runat="server" Text='<%# Eval("Name") %>' />
</td>
</tr>
<tr>
<td colspan="2">
<asp:Label ID="LblDescription" runat="server" Text='<%# Eval("Description").ToString().Substring(1, 240) + "..." %>'/>
<asp:HyperLink ID="HlMore" runat="server" NavigateUrl='<%#"~/Project/ViewProject.aspx?projectId=" + Eval("ProjectID") %>' Text="More" />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</asp:Panel>
protected override void OnPreRender(EventArgs e)
{
var table = Projects.GetTableWithProjects();
if (table.Rows.Count > 0)
{
rptrProjects.DataSource = table;
rptrProjects.DataBind();
}
else
{
pnlDisplayProjects.Visible = false;
Master.PrintMessage("There are no projects.");
}
}
采纳答案by IordanTanev
string dec = "description";
string result = dec.Substring( 0, dec.Length > 240 ? 240 : dec.Length )
回答by David
It's a bit of a hack, but the simplest method would be to change:
这有点黑客,但最简单的方法是更改:
Eval("Description").ToString().Substring(1,240)
to
到
Eval("Description").ToString().PadRight(240).Substring(1, 240)
I'm not sure about the performance considerations on this, though, if therre are a lot of items.
但是,如果有很多项目,我不确定对此的性能考虑。
回答by Jon Skeet
I would suggest you write a separate extension method if you're using .NET 3.5. Something like this:
如果您使用 .NET 3.5,我建议您编写一个单独的扩展方法。像这样的东西:
public static string SafeSubstring(this string text, int start, int length)
{
return text.Length <= start ? ""
: text.Length - start <= length ? text.Substring(start)
: text.Substring(start, length);
}
Basically that's a version of Substring
which will never throw an exception unless start or length is negative (in which case I don't know what it could sensibly return).
基本上这是一个Substring
永远不会抛出异常的版本,除非 start 或 length 为负(在这种情况下我不知道它可以明智地返回什么)。
You'd call it like this:
你会这样称呼它:
Eval("Description").ToString().SafeSubstring(1, 240) + "..."
The downside of this is that it will include the ellipsis (...) even if it's not actually truncated the string at all...
这样做的缺点是它会包含省略号 (...),即使它实际上根本没有截断字符串...
回答by Nathan Wheeler
If you REQUIRE 240 characters in that place for some reason, you can cast that field coming out of the database as a char(241)
in which case it will always be 241 characters, with padding to the right if the content of the field was shorter than 241 characters. Then you can still strip off the first character with the Substring(1, 240)
as you are right now.
如果出于某种原因在该位置需要 240 个字符,则可以将该字段从数据库中转换为 a,char(241)
在这种情况下它将始终为 241 个字符,如果该字段的内容少于 241 个字符,则向右填充. 然后你仍然可以Substring(1, 240)
像现在一样用 去掉第一个字符。
Although, I must wonder if you're not wanting to do a Substring(0, 240)
which wouldn't throw an exception if the string was shorter than 240 characters, and would start at the beginning of the string, rather than the 2nd character.
虽然,我必须想知道如果Substring(0, 240)
字符串短于 240 个字符并且会从字符串的开头而不是第二个字符开始,您是否不想做一个不会引发异常的操作。
回答by ewrankin
Another option is to write a a method that you call so your eval turns into:
另一种选择是编写一个你调用的方法,这样你的 eval 就会变成:
<%# GetString(Container.DataItem) %>
So in the method you could check to make sure that the item is NOT null because you may bomb out calling .ToString on a NULL item. Then you can evaluate the container item and pass in the length to the substring call.
因此,在该方法中,您可以检查以确保该项目不为空,因为您可能会在 NULL 项目上调用 .ToString 进行轰炸。然后您可以评估容器项并将长度传递给子字符串调用。
回答by Nick
Text='<%# Eval("Description").ToString().Substring(1, Math.Min(240, Eval("Description").ToString().Length - 1)) + "..." %>'
回答by Phil Haselden
An extension method:
一种扩展方法:
public static string SafeSubstring(this string text, int start, int length)
{
if (start >= text.Length)
return "";
if (start + length > text.Length)
length = text.Length - start;
return text.Substring(start, length);
}
回答by Protector one
I would write a static helper function or extension method.
我会写一个静态辅助函数或扩展方法。
public static string SafeSubstring(string str, int start, int count){
int n = str.Length;
return str.Substring(Math.Min(start,n), Math.Min(count,n));
}
Then use:
然后使用:
<%# SafeSubstring(Eval("Description",""), 1, 240) %>
(And if you also want to be safe for negative integers, throw some Math.Max
's with 0 in there.)
(如果您还想对负整数保持安全,请在其中抛出一些Math.Max
0。)
回答by superlogical
Based on Jon Skeet's answer, I think it should be checking for null or else it's not exactly a safe method :)
基于 Jon Skeet 的回答,我认为它应该检查 null 否则它不是一个完全安全的方法:)
public static string SafeSubstring(this string text, int start, int length)
{
if (text == null) return null;
return text.Length <= start ? ""
: text.Length - start <= length ? text.Substring(start)
: text.Substring(start, length);
}
回答by skini
You can use LINQ as below:
您可以使用 LINQ,如下所示:
string someString = "abcde";
string subStr = string.Join("", someString.Take(240));