【问题标题】:C# code displaying all lines until you found that search word from your textboxC# 代码显示所有行,直到您从文本框中找到该搜索词
【发布时间】:2018-05-02 22:05:51
【问题描述】:
string[] hay = GetAllLines(filename); 
string needle = txtToonTotTekst.Text; 
string alertmsg = "";
string msg = "";
int keywordfound = 0;
int lineno = 0;
while (lineno <= hay.Length) 
{
    msg += hay[lineno];//msg = msg + hay[lineno];
    lineno++;

    if ((hay[lineno].IndexOf(needle) == -1))
    {
        keywordfound = 0;
        continue;
    }
    else
    { /*this means search word was found */
        keywordfound = 1;
        alertmsg = msg;
        //if coffee found in search string 
    }

    if (keywordfound == 1)
    {
        alertmsg = msg;
    }
    lineno++;
}

if (alertmsg == "")
{
    alertmsg = "Keyword not found";
}

SchrijfUitvoer("Tekst tonen tot zoektekst + "txtToonTotTekst.Text, alertmsg);

我的问题是关于索引超出数组范围的错误.....通常,当您输入要搜索的单词时,它会显示文本文件中的文本,并在找到搜索词时显示行数

【问题讨论】:

  • 你能提供错误信息吗?它指向哪一行(堆栈跟踪)?
  • if ((hay[lineno].IndexOf(needle) == -1))
  • hay[] 是一个数组

标签: arrays string while-loop textbox indexoutofboundsexception


【解决方案1】:

你有两次lineno++,我猜最后应该只有一次。 C# 中的集合是从零开始的,所以:

while (lineno <= hay.Length) 

应该是:

while (lineno < hay.Length) 

如果 Array 的长度为 5,则最后一个元素为 [4]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-04
    • 2016-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多