C# StartIndex 不能小于零。- 尝试更改字符串时出错

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17282058/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:01:40  来源:igfitidea点击:

StartIndex cannot be less than zero. - Error when trying to change a string

c#.netstring

提问by Nave Tseva

I have the following C# code:

我有以下 C# 代码:

ArticleContent = ds1.Tables[0].Rows[i]["ArticleContent"].ToString();

if (ArticleContent.Length > 260)
{
   ArticleContent = ArticleContent.Remove(ArticleContent.IndexOf('.', 250)) + "...";
}

The problem here is that I get this error message:

这里的问题是我收到此错误消息:

StartIndex cannot be less than zero.

StartIndex 不能小于零。

Why and how can I fix it?

为什么以及如何修复它?

采纳答案by D Stanley

You are getting that error because there is no '.'character on or after index 250, so IndexOfreturns -1. You then try to remove the character at position -1which gives you the error you are seeing.

您收到该错误是因为'.'索引 250 上或之后没有字符,因此IndexOf返回-1. 然后,您尝试删除位置处的字符,-1这会给您带来您所看到的错误。

Also realize that Removeonly removes one character at that position, not everything after that position. What I suspectyou want is:

还要意识到Remove只删除该位置的一个字符,而不是该位置之后的所有字符。我怀疑你想要的是:

if (ArticleContent.Length > 260)
{
   int lastPeriod = ArticleContent.LastIndexOf('.');
   if(lastPeriod < 0)
      lastPeriod = 257;  // just replace the last three characters
   ArticleContent = ArticleContent.Substring(0,lastPeriod) + "...";
}

That will add ellipses to the string, making sure it is no longer that 260 characters and breaking at a sentence if possible.

这将在字符串中添加省略号,确保它不再是 260 个字符,并在可能的情况下断句。

回答by Crab Bucket

If the below can't find the '.' it will return -1 which will not be valid for the RemoveAt

如果下面找不到'.' 它将返回 -1,这对 RemoveAt 无效

ArticleContent.IndexOf('.', 250)

回答by Kamil

As others wrote - when your ArticleContenthas no '.' character - method .Remove()will return -1.

正如其他人所写-当您ArticleContent没有 '.' 时 字符 - 方法.Remove()将返回 -1。

I suggest to add one more condition in your if:

我建议在您的if:

if (ArticleContent.Length > 260 && ArticleContent.Contains('.'))
{
    ArticleContent = ArticleContent.Remove(ArticleContent.IndexOf('.', 250)) + "...";
}

回答by armen.shimoon

There's a chance that there is no . after position 250. You need to check first:

有可能没有。在位置 250 之后。您需要先检查:

ArticleContent = ds1.Tables[0].Rows[i]["ArticleContent"].ToString();

var periodPosition = ArticleContent.IndexOf('.', 250);
if (ArticleContent.Length > 260 && periodPosition >= 0)
{
   ArticleContent = ArticleContent.Remove(ArticleContent.IndexOf('.', 250)) + "...";
}

回答by Derek W

Source of error:'.'does not appear after index 250. The IndexOfmethod returns -1 in this case.

错误来源:'.'不会出现在索引 250 之后IndexOf。在这种情况下,该方法返回 -1。

While others have just identified the source of the error, I will also post a fix to your problem.

虽然其他人刚刚确定了错误的来源,但我也会发布解决您的问题的方法。

Solution:Use the LastIndexOfmethod:

解决LastIndexOf方法:使用方法:

if (ArticleContent.Length > 260)
{
   if (ArticleContent.Remove(ArticleContent.LastIndexOf('.') != -1)
   {
       ArticleContent = String.Concat(ArticleContent.Remove(ArticleContent.LastIndexOf('.')), "...");
   }
   else
   {
       ArticleContent = String.Concat(ArticleContent.Substring(0, 257), "...")
   }
}

回答by Meredith Poor

ArticleContent = ds1.Tables[0].Rows[i]["ArticleContent"].ToString();
if (ArticleContent.Length > 260)
{
    if (ArticleContent.Substring(250).Contains("."))
    {
        ArticleContent = ArticleContent.Remove(ArticleContent.IndexOf('.', 250)) + "...";
    }
    else
    {
        ArticleContent = ArticleContent.Remove(ArticleContent.Substring(0, 250)) + "...";
    }
}

回答by AdmiralSnackbar

It's clear why it's failing, but what exactly are you trying to do? If it's simply to truncate a string to a particular length and indicating the truncation, I might suggest the extension method listed below. It's usage is simply:

很明显它失败的原因,但你到底想做什么?如果只是将字符串截断为特定长度并指示截断,我可能会建议使用下面列出的扩展方法。它的用法很简单:

ArticleContent = ArticleContent.Truncate(250);

Truncate extension method:

截断扩展方法:

public static string Truncate(this string pThis, int pLength)
{
    if (string.IsNullOrEmpty(pThis))
        return pThis;

    if (0 >= pLength)
        return string.Empty;

    var lTruncatedString = pThis;
    const string lEllipses = @"…";

    if (pThis.Length > pLength)
    {
        var lSubstringLength = Math.Max(pLength - lEllipses.Length, 0);
        lTruncatedString = pThis.Substring(0, lSubstringLength) + lEllipses;
        if (lTruncatedString.Length > pLength)
            lTruncatedString = lTruncatedString.Substring(0, pLength);
    }

    return lTruncatedString;
}

I hope this helps.

我希望这有帮助。