zoukankan      html  css  js  c++  java
  • 采用c#实现功能1

          看了好多c#的菜鸟教程不如自己开始动手打代码,最终实现了功能一,参考了网上的wordcount代码发现无论是c++还是c#大部分采用的是哈希表的方法实现的,本来还想仅用循环实现遍历句子中的所有字符,即发现"  "就total++,但是考虑到功能二的单词数变得很多,这样做时间相对来说会慢一点,因此选择了hash表来实现功能。因为仅是一个句子,所以只需要将句子中的空格split就可以了,但在解决过程中我碰到的最大问题是C:Usersdell-pcDesktopwccwccInterface1.cs(24,24): 错误 CS0029: 无法将类型“string[]”隐式转换为“string”,查了好久最终解决了这个问题~

    using System;
    using System.IO;
    using System.Text;
    using System.Collections;
    using System.Collections.Generic;
    
    namespace wordcount
    {
        class Program
        {
    
            static void Main(string[] args)
            {
                Console.Write(">type ");
                string textFileName;
                textFileName = Console.ReadLine();
                //读取文件内容
                StreamReader sreader = new StreamReader(@"C:Usersdell-pcdesktop	est1.txt");
                //输出文件内容
                string aword = sreader.ReadLine();
                Console.WriteLine(aword);
                Console.WriteLine();
                char c = ' ';
                //除去' '后的字符串数组
                string[] s = aword.Split(c);
                //建立哈希表
                Hashtable ha = new Hashtable();
                for (int i = 0; i < s.Length; i++)
                {
                    //判断哈希表中是否有文本
                    if (ha.ContainsKey(s[i]))
                    {
                        ha[s[i]] = (int)ha[s[i]] + 1;
                    }
                    else
                    {
                        ha.Add(s[i], 1);
                    }
                }
                string[] arrKey = new string[ha.Count];//存键
                int[] arrValue = new int[ha.Count];//存值
                ha.Keys.CopyTo(arrKey, 0);
                ha.Values.CopyTo(arrValue, 0);
                Console.WriteLine(">wf -s test.txt");
                Console.WriteLine("total " + ha.Count);
                Console.WriteLine();
                Array.Sort(arrValue, arrKey);//排序
                for (int i = arrKey.Length - 1; i >= 0; i--)
                {
                    if ((string)arrKey[i] != "")
                    {
                         Console.Write(arrKey[i].ToString().PadRight (12)+" ");
                         Console.WriteLine(arrValue[i].ToString());
                    }
                }
            }
        }
    }

    下面是我的代码:

    最终实现结果为:

  • 相关阅读:
    Hive_元数据配置到MySQL
    第一篇
    mysql查询结果添加序列号
    java中正则表达式
    java位运算
    正数负数原码,反码,补码
    各进制间相互转换
    linux下默认安装jdk路径查找
    localhost:8080/manager/status无法访问403 Access Denied
    Idea官网指南
  • 原文地址:https://www.cnblogs.com/yuanyue-nenu/p/7537713.html
Copyright © 2011-2022 走看看