簡體   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