【问题标题】:How do i acces individual Values in a hash table如何访问哈希表中的单个值
【发布时间】:2020-03-27 07:08:07
【问题描述】:

我有一个任务,我必须接受一个字符串输入并对其应用 zipfs 法则。我在访问哈希表中的值时遇到问题。每当我发现一个已经存在的单词时,我都应该更新 wordcounter +1。最终发生的是计数器适用于哈希表中的所有值,而我得到的数字高得离谱。我无法理解我应该如何为每个键值提供一个单独的计数器

代码如下:

using System;
using Spire.Doc;
using System.Collections;
using System.Collections.Generic;

namespace Zipf
{
    class Program
    {
        public static Hashtable wordRegister;


        static void Main(string[] args)
        {
            String[] ArrLoop = TextSplitter();
            int[] wordCount = new int[ArrLoop.Length];
            int count = 1;
            wordRegister = new Hashtable();


            for(int i = 0; i < ArrLoop.Length; i++)
            {
                if (wordRegister.ContainsKey(ArrLoop[i]))
                {
                    // here is where im having trouble
                    wordRegister[ArrLoop[i]] = count += 1;

                }
                else
                {
                    wordRegister.Add(ArrLoop[i], count);
                }



            }
            foreach (DictionaryEntry pair in wordRegister)
            {
                Console.WriteLine($"Key : {pair.Key} ; Forekomster : {pair.Value}");
            }
            Console.ReadLine();


        }

        public static String WordString()
        {
            Document doc = new Document();
            doc.LoadFromFile(@"C:\Users\xxx\Desktop\2.g\IDO.docx");

            String textString = doc.GetText();

            return textString;

         }

        public static string[] TextSplitter()
        {
            string s = WordString();
            String[] wordArr = s.Split();

            return wordArr;
        }




}

}

【问题讨论】:

  • 您应该首先能够回答“什么是哈希表,它为什么有用?”这个问题。如果你能做到这一点,你可能会对你的代码有更好的了解。
  • 旁注,使用字典可能比使用哈希表更容易。
  • Votung 关闭为“广泛”,因为由于问题显示的编程误解的数量,这需要解释的人。 (也许经常是你大学的优秀学生喝咖啡)

标签: c# hashtable


【解决方案1】:

您不需要 count 变量。您正在递增所有条目共有的计数器。

请尝试这样做以保持计数彼此不同:

wordRegister[ArrLoop[i]] += 1;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-06
    • 2013-03-22
    • 2013-10-11
    • 2014-05-06
    • 2013-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多