繁体   English   中英

我如何计算字符串列表中的单词

[英]how do i count the words in a string list

我经常遇到超载问题,我已经查过了,但似乎没有什么像我的情况......我希望这里的人可以帮助我。 我的代码示例如下所示。

string s = textbox.text;
char[] delimiter = {' '};
string[] word = s.split(delimiter); //this gets a set of words from s.split
for (int i = 0; i <= word.length; i++) //I also tried word.count()
{
    int ii = 0;
    int counter = wordlist.count;
    bool test1 = false;
    while (test1 == false || ii != counter +1)
    {
        if (word[i] == wordlist[ii]) //this is where it gets stuck. It wants to load more word[i] than what there are in the list... 
        {
            //function gets preformed
            test1 = true;
        }
        else
        {
            ii++;
        }            
    }
}

请帮助我,我脚本的这一部分至关重要...谢谢您的时间!

不应该是string[] words = s.Split(' ');

即使我们说你的words.Split(' '); 那么它应该是string[] words = word而不是string[]=word

并计算该数组中有多少单词只需执行int howManyWords = words.Length;

此外,如果您想通过循环次数与列表中的单词一样多,您应该这样做:

for(int i = 0; i < words.Lenght; i++)
{
    //Do your stuff
}

虽然您的问题很不清楚(您至少应该发布您遇到的错误,这会使回答更容易),但您在评论中已将其清除。 您得到的是索引超出范围异常。

你需要改变你的循环

for (int i = 0; i <= word.length; i++)

for (int i = 0; i < word.length; i++) // preferable

或者

for (int i = 0; i <= word.length - 1; i++) // not preferable

数组的索引为 0 而不是 1。 length 属性将为您提供数组中元素的总数。 当您到达最后一个索引时,i 的值将大于元素数,因为您从 0 开始计数。

您还需要更改 while 循环,因为那里发生了超出范围的异常。 它是同样的问题,除了这次你添加了一个让它变得更糟。

while (test1 == false && ii != counter - 1)

将其更改为减号,使其永远不会超出范围。 还将逻辑更改为 && 而不是 || 使用 or 当它找到匹配项时,它永远不会增加 ii,因此它会永远停留在一段时间内。

一旦找到匹配项,您还想跳出循环。

好的,所以我发现了我的问题。 那是因为 wordlist[] 中没有可供它阅读的单词……我的错!

下次我应该放在预防方法中......

不过还是谢谢大家的帮助! 代码现在可以正常工作了!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM