C#字符串题目

老师给小学生门布置了一些作业,让它们按照一个模版写一些字符串交上来,同学们把作业交上来了,问题来了,这么多的作业老师批改不过来,现在请你帮老师写一个程序,帮助老师确定各个字符串是否合格。首先老师有一个匹配模版,比如是“aa[123]bb”这一个字符串,同学们交的各种作业字符串如aa1bb、aa2bb、aa3bb都算是正确匹配看,而aacbb就是错误的字符串。(即待查字符串对应于模版方括号内的部分,应该为方括号内字符串的一个子字符)。我们需要做的就是按照模版,找出正确的字符串和所在的行。输入输入的第一行为一个整数n,表示有多少个学生的作业,即有多少行需要检查的字符串。(1<=n<=50) 中间为n行字符串,代表着n个学生们写的作业。每个字符串长度小于50。 最后一行为1行字符串,代表着老师给的匹配模板。输出输出合格的字符串的行号和该字符串。(中间以空格隔开)

样例输入

4

Aab

a2B

ab

ABB

a[a2b]b

样例输出

1 Aab

2 a2B

4 ABB

提示

被检测的字符串中只有数字和字母

请问这个的算法和程序是怎样的

 

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace 作业
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             int n;
14             n = Convert.ToInt32(Console.ReadLine());
15             string[] sentences = new string[n];
16             string[] temp = new string[n];
17             for (int i = 0; i < sentences.Length; i++)
18             {
19                 sentences[i] = Console.ReadLine();
20                 temp[i] = sentences[i].ToUpper();
21             }
22             string template = Console.ReadLine();
23             template = template.ToUpper();
24             //至此,全部的输入完成
25             //首先,分析模板
26             int begin = template.IndexOf('[');//模板中'['的索引
27             int end = template.IndexOf(']');//模板中']'的索引
28             string keyChar = template.Substring(begin+1, end - begin - 1);//模板中中括号里的内容
29             string beginStr = template.Substring(0, begin);//模板中'['之前的部分
30             string endStr = template.Substring(end + 1, template.Length - end - 1);//模板中']'之后的部分
31             //模板分析完毕
32             for (int i = 0; i < n; i++)
33             {
34                 string s = temp[i];
35                 if (s.Length == beginStr.Length + endStr.Length + 1)//学生的作业长度要符合标准
36                 {
37                     if (s.StartsWith(beginStr) || s.EndsWith(endStr))//检查学生作业的开头与结尾
38                     {
39                         if (keyChar.Contains(s[begin]))
40                         {
41                             Console.WriteLine("{0}\t{1}", i + 1, sentences[i]);//学生作业中的可变内容
42                         }
43                     }
44                 }
45             }
46 
47             Console.ReadKey();
48         }
49     }
50 }

出现过的错误:经常下意识的认为索引从1开始

posted @ 2015-07-14 08:55  不如隐茶去  阅读(691)  评论(0编辑  收藏  举报