C# 字符串长度并与int进行比较
为什么这不起作用? 例如,如果striserlength返回300,则为真。 如果返回例如37,则为false。。即使它应该是反向的 我的代码:C# 字符串长度并与int进行比较,c#,substring,string-length,C#,Substring,String Length,为什么这不起作用? 例如,如果striserlength返回300,则为真。 如果返回例如37,则为false。。即使它应该是反向的 我的代码: @{ int teaserLength = item.TeaserText.Length; } @if (teaserLength >= 75) { @item.TeaserText } else { @item.TeaserText.Substring(1, 75) } 为什么长度为37的摘要文本会给出 Arg
@{
int teaserLength = item.TeaserText.Length;
}
@if (teaserLength >= 75)
{
@item.TeaserText
}
else {
@item.TeaserText.Substring(1, 75)
}
为什么长度为37的摘要文本会给出
ArgumentOutOfRangeException
Index and length must refer to a location within the string.
在子字符串上?子字符串中的“起始”索引是从零开始的,并且只有在长度为75或更长时才需要子字符串:
@if (teaserLength >= 75)
{
@item.TeaserText.Substring(0, 75)
}
else {
@item.TeaserText
}
或者只是
@item.TeaserText.Substring(0, Math.Min(teaserLength, 75))
子字符串
中的“起始”索引是从零开始的,如果长度大于等于75,则只需要子字符串:
@if (teaserLength >= 75)
{
@item.TeaserText.Substring(0, 75)
}
else {
@item.TeaserText
}
或者只是
@item.TeaserText.Substring(0, Math.Min(teaserLength, 75))
再次阅读您自己的
if
语句
@if (teaserLength >= 75)
{
@item.TeaserText
}
else {
@item.TeaserText.Substring(1, 75)
}
如果striserlength
大于或等于75,则使用文本,否则使用子字符串
不能获取长度小于75的字符串的长度为75的子字符串
要解决此错误,只需将
=
操作符切换为即可再次读取自己的if
语句
@if (teaserLength >= 75)
{
@item.TeaserText
}
else {
@item.TeaserText.Substring(1, 75)
}
如果striserlength
大于或等于75,则使用文本,否则使用子字符串
不能获取长度小于75的字符串的长度为75的子字符串
要解决此错误,只需将=
运算符切换为即可。另一种方法是使用函数:
@{
int maxCharsToDisplay = Math.Min(item.TeaserText.Length, 75);
}
@item.TeaserText.Substring(0, maxCharsToDisplay);
对于值小于75的情况,Min
将返回该长度;如果该值较大,将返回75
。您最多只能有75个字符。另一种方法是使用该函数:
@{
int maxCharsToDisplay = Math.Min(item.TeaserText.Length, 75);
}
@item.TeaserText.Substring(0, maxCharsToDisplay);
对于值小于75的情况,Min
将返回该长度;如果该值较大,将返回75
。您最多只能有75个字符。另一种方法是使用System.Linq
,只需获取所需的最大项数(75个),然后Concat
即可:
string.Concat(item.TeaserText.Take(75));
另一种方法是使用System.Linq
,只需获取所需的最大项数(75),然后Concat
即可:
string.Concat(item.TeaserText.Take(75));
因为您的字面意思是如果字符串长度小于75,则取子字符串
?子字符串从索引0开始。使用数组的方式相同。@IanH。我不是说,如果streamerText小于或等于75,请使用streamer text。如果较大,则使用子字符串?您的意思是,如果teaserText小于75,则从索引1(即第二个字符)开始,获取75个字符的子字符串(可获取的字符数不多,只有37个!)。您想让它做什么?您可以完全去掉striserlength
变量和if/else
,然后返回@item.triserText.Substring(0,Math.Min(item.triserText.Length,75))
因为您的字面意思是如果字符串长度小于75,则取子字符串
?子字符串从索引0开始。使用数组的方式相同。@IanH。我不是说,如果streamerText小于或等于75,请使用streamer text。如果较大,则使用子字符串?您的意思是,如果teaserText小于75,则从索引1(即第二个字符)开始,获取75个字符的子字符串(可获取的字符数不多,只有37个!)。您想让它做什么?您可以完全去掉striserlength
变量和if/else
,然后返回@item.triserText.Substring(0,Math.Min(item.triserText.Length,75))代码>为什么不修正你的答案,而不是仅仅注意到你会得到一个例外?@DStanley我的答案怎么了?我说明了导致错误的原因并提供了解决方案。这没有错(我也没有投反对票),但将索引修复纳入答案比添加旁注更完整。@DStanley With answer,您是指代码段吗?答案中提供的片段与问题中的片段完全相同-我将其包括在内只是为了让读者在阅读时意识到错误。为什么不修正你的答案,而不是仅仅注意到你会得到一个例外?@DStanley我的答案怎么了?我说明了导致错误的原因并提供了解决方案。这没有错(我也没有投反对票),但将索引修复纳入答案比添加旁注更完整。@DStanley With answer,您是指代码段吗?答案中提供的片段与问题中的片段完全相同——我将其包括在内只是为了让读者在阅读时意识到错误。