设计一个Windows应用程序,输入一行字符,检索是否存在重复的二字词汇(由两个字符组成的字符),输出重复的次数
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace _3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int n = 0;
string[] words = new string[100];
int[] number = new int[100];
for (int i = 0; i < textBox1.Text.Length - 2; i++)
{
bool flag = false; //判断单词是否发生重复
string sf = textBox1.Text.Substring(i, 2);//substring()的作用就是截取父字符串的某一部分.第一个参数int为开始的索引,对应String数字中的开始位置;第二个参数是截止的索引位置,对应String中的结束位置
for (int j = i + 2; j < textBox1.Text.Length - 2; j++)
{
string sright = textBox1.Text.Substring(j, 2);
if (sf == sright)
{
number[n]++;
if (Array.IndexOf(words, sright) == -1)
{
flag = true;
words[n] = sright;
}
}
}
if (flag == true)//如果找到了重复的单词,单词数组中的索引值加1
{
n++;
}
}
label2.Text = string.Format("一共有{0}个重复的词汇", n);//Format()用于填充格式化字段里面的内容。即将Format()的参数n填充到{0}中
for (int z = 0; z < n; z++)
{
if(!String.IsNullOrEmpty(words[z]))//判断字符串是空引用,或值为空
label2.Text += string.Format("“{0}”重复了{1}次!", words[z], number[z] + 1);
}
}
}
}
测试结果: