编写C# 控制台应用程序,判断用户输入的字符串中是否存在重复

如题所述

第1个回答  2018-04-01
using System;
using System.Collections.Generic;

namespace Test
{
class Program
{
public static void Main(string[] args)
{
string substr,line=Console.ReadLine();
Dictionary<string,int> d=new Dictionary<string,int>();

if(line!=line.ToLower())
{
Console.WriteLine("Inputting illegal characters");
return ;
}
for(int index=0;index<line.Length-1;index++)
{
substr=line.Substring(index,2);
if(d.ContainsKey(substr))
d[substr]++;
else
d.Add(substr,1);
}
foreach(string k in d.Keys)
{
if(d[k]>1)
Console.WriteLine("{0} {1}",k,d[k]);
}
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
}本回答被提问者和网友采纳
第2个回答  2018-04-04
这个题要注意的一点是,只输出重复的小字符串,所以如果一个小字符串出现的次数不足两次,就不需要去输出它。
下面这个程序用的是非常基础的c#语言,还有很多地方可以改进,不过至少调试时输出是正确的。
using System;
using System.Collections.Generic;
namespace c1_4
{
class Program
{
static void Main(string[] args)
{
string c = Console.ReadLine();
int n = 1;
int i, k, t = 0, r = 0;
char ak;
for (i = 0; i < c.Length; i++)
{
ak = c[i];
if ((ak < 97) || (ak > 122))
r = 1;//判断是否存在非小写字母,即指大写字母、数字、符号等。
}
if (r == 1)
Console.WriteLine("Inputting illegal characters");
else
{
int[] s = new int[100];//存储小字符串出现次数。
string[] ck = new string[1000];//存储小字符串种类。
for (i = 0; i < 100; i++)
{ s[i] = 0; ck[i] = "a"; }
string b;
for (i = 0; i < c.Length - 1; i++)
{
b = c.Substring(i, 2);//从大字符串中截取小字符串。
for (k = 0; k < n; k++)
if (b.Equals(ck[k]))
{
t = 1;
s[k]++;
}//如果小字符串在之前已被记录过一次,把它的出现次数加一。
if (t == 0)
{
ck[n] = b;
s[n] = 1;
n++;
}//如果小字符串不曾被记录过,那就新开一个位置,把它放进去。
t = 0;//重制判断小字符串是否重复的变量。
}
for (i = 0; i < n; i++)
if (s[i] != 0) Console.WriteLine(ck[i] + " {0}", s[i]);
Console.ReadLine();
}
}
}
}
相似回答