求助:一个c#编程题目
问题:键盘输入如“ABefgt”的字母串,使用C#编程实现计算每个字母出现次数的程序。
当键盘输入字符串后,如何遍历和比较字符串中每个字符是否相等呀?
(本人认真学习当中)
希望大家用代码支持我下,谢了
[解决办法]
private void NewMethod() { List<string> list = new List<string>();//List string s = string.Empty; if (textBox1.Text.Trim() != "") { char[] c = textBox1.Text.Trim().ToCharArray(); for (int i = 0; i < c.Length; i++) { int count = 0; for (int j = 0; j < c.Length; j++)//相同的累加 { if (c[i] == c[j]) count++; } s = c[i] + "=" + count; if (list.IndexOf(s) == -1)//如果存在就不用加 { list.Add(s); this.textBox2.Text += s + "\r\n"; } } } }
[解决办法]
不用list,用list是多余的。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Countstring
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("请输入您要查询的字符串:\n");
string s = Console.ReadLine();
Console.WriteLine("该字符串中出现的字符的次数分别如下:\n");
int count=0;
for (int i = 0; i < s.Length;i++ )
{
//比较该字符在前面是否出现过?是,就跳过,因为前面统计了;否,开始统计
int frontifsame = 0;
for (int j = i - 1; j >= 0; j--)
{
if (s[j] == s[i])
{
frontifsame++;
break;//比较该字符在前面是否出现过?是,就跳过,因为前面统计了;
}
}
if (frontifsame == 0)//比较该字符在前面是否出现过?否,开始统计
{
count = 1;
for (int j = i + 1; j < s.Length; j++)
{
if (s[j] == s[i])
{
count++;
}
}
Console.WriteLine("{0} 在您输入的字符串中出现的次数为: {1}.\n", s[i], count);
}
}
}
}
}
[解决办法]
键盘输入如“ABefgt”的字母串,使用C#编程实现计算每个字母出现次数的程序。
都不很好 用sortlist
static void Main(string[] args) { string data = "asd646uio4asda .sdjhglajsdoajam] 4uio64aaaksd;ka;s"; SortedList<char, int> charCount = new SortedList<char, int>(); foreach (char i in data) { if (!charCount.ContainsKey(i)) { charCount.Add(i, 1); } else { charCount[i]=charCount[i]+1; } } foreach (KeyValuePair<char, int> i in charCount) { Console.WriteLine(" "+i.Key+": "+i.Value); } }
[解决办法]
粗略做了个,lz看看
class Program
{
public static int numWord(string word, string[] wordList)//查询字母在字符数组中出现的次数查询
{
int cout = 0;
for (int i = 0; i < wordList.Length; i++)
{
if (word.Equals(wordList[i], StringComparison.Ordinal))
cout++;
}
return cout;
}
static void Main(string[] args)
{
int cout ; //定义字母出现的查询
string word; //要查询的字母
string strWordlist;//要输入的字符串
string[] wordList = new string[100];
Console.WriteLine("请输入字符串数组");
strWordlist = Console.ReadLine();
for (int i = 0; i < strWordlist.Length; i++) //讲输入的字符串放入字符数组中
{
wordList[i] = strWordlist.Substring(i, 1);
}
Console.WriteLine("请输入你要查询的字母");
word = Console.ReadLine();
cout=numWord(word,wordList);
Console.WriteLine(cout);
Console.ReadLine();
}
[解决办法]
这个保证不难理解
class Program
{
static void Main(string[] args)
{
string a = "asdfeDSds";
for (int i = 'A'; i <= 'Z'; i++)
{
Console.WriteLine(((char)i).ToString()+":"+(a.Length-a.Replace(((char)i).ToString(),"").Length));
}
for (int i = 'a'; i <= 'z'; i++)
{
Console.WriteLine(((char)i).ToString() + ":" + (a.Length - a.Replace(((char)i).ToString(), "").Length));
}
}
}