带有ascii代码的C#程序的问题 [英] Question of a C# programm with ascii code

查看:92
本文介绍了带有ascii代码的C#程序的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是c#的初学者并且有一个问题,

如何用ascii代码计算文本的每个单个字符的出现



我尝试过:



Console.WriteLine(text:);

txt = Console.ReadLine()

解决方案

默认情况下C#不使用ASCII - 它使用更宽的Unicode(16位而不是7或8用于扩展ASCII)。当您使用Console.readLine时,您获得的字符串是一个Unicode字符串,包含Unicode char s。对于真正的ASCII,你必须使用一个字节数组,并翻译Unicode:

 string s = Console.ReadLine(); 
byte [] bytes = System.Text.Encoding.ASCII.GetBytes(s);





但是...对于大多数不相关的输入,如果你是初学者,这可能是你的功课算上字符。

最简单的方法?排序他们。然后重复是彼此相邻的,你可以用一个简单的循环来计算它们:

1)将计数设置为零。

2)将currentChar设置为'\ 0'

3)循环排序数据中的每个字符

3.1)currentChar是否与循环字符相同?

3.1。 1)是:递增计数

3.1.2)否:是currentChar'\0'?

3.1.2.1)是:递增计数,将currentChar设置为循环字符

3.1.2.2)否:打印currentChar和count,将count设置为1,将currentChar设置为循环char

4)循环后,打印currentChar并计数


您可以随时使用 Linq 。将字符串转换为 char 类型的 List 。对列表进行排序。将字符按字符分组为具有两个字段Letter和Count的新匿名类型。 Letter是组密钥,Count是组项目的总数。枚举查询并将结果打印到控制台。


I'm a beginner in c# and have a question ,
how do i count the occurrence of each single character of a text with the ascii code

What I have tried:

Console.WriteLine("text: ");
txt = Console.ReadLine()

解决方案

C# doesn't use ASCII by default - it uses Unicode which is wider (16 bit instead of 7 or 8 for Extended ASCII) . when you use Console.readLine the string you get is a Unicode string, containing Unicode chars. For "true ASCII" you would have to use an array of bytes, and translate the Unicode:

string s = Console.ReadLine();
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(s);



But ... for most input that's irrelevant, and if you're a beginner this is probably your homework to count characters.
Easiest way? Sort them. Then the repetitions are all next to each other and you can count them with a simple loop:
1) Set count to zero.
2) Set currentChar to '\0'
3) Loop through each character in the sorted data
3.1) Is currentChar is the same as the loop character?
3.1.1) Yes: increment count
3.1.2) No: Is currentChar '\0'?
3.1.2.1) Yes: increment count, set currentChar to loop character
3.1.2.2) No: Print currentChar and count, set count to 1, set currentChar to loop char
4) After loop, print currentChar and count


You could always use Linq. Convert the string to a List of type char. Sort the List. Group the characters by character into a new anonymous type with two fields, Letter and Count. Letter is the group key and Count is the total count of group items. Enumerate the query and print the results to the console.


这篇关于带有ascii代码的C#程序的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆