您的位置:首页 > 编程语言 > C#

C#字符串题目

2015-07-14 08:55 447 查看
老师给小学生门布置了一些作业,让它们按照一个模版写一些字符串交上来,同学们把作业交上来了,问题来了,这么多的作业老师批改不过来,现在请你帮老师写一个程序,帮助老师确定各个字符串是否合格。首先老师有一个匹配模版,比如是“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

提示

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

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 作业
{
class Program
{
static void Main(string[] args)
{
int n;
n = Convert.ToInt32(Console.ReadLine());
string[] sentences = new string
;
string[] temp = new string
;
for (int i = 0; i < sentences.Length; i++)
{
sentences[i] = Console.ReadLine();
temp[i] = sentences[i].ToUpper();
}
string template = Console.ReadLine();
template = template.ToUpper();
//至此,全部的输入完成
//首先,分析模板
int begin = template.IndexOf('[');//模板中'['的索引
int end = template.IndexOf(']');//模板中']'的索引
string keyChar = template.Substring(begin+1, end - begin - 1);//模板中中括号里的内容
string beginStr = template.Substring(0, begin);//模板中'['之前的部分
string endStr = template.Substring(end + 1, template.Length - end - 1);//模板中']'之后的部分
//模板分析完毕
for (int i = 0; i < n; i++)
{
string s = temp[i];
if (s.Length == beginStr.Length + endStr.Length + 1)//学生的作业长度要符合标准
{
if (s.StartsWith(beginStr) || s.EndsWith(endStr))//检查学生作业的开头与结尾
{
if (keyChar.Contains(s[begin]))
{
Console.WriteLine("{0}\t{1}", i + 1, sentences[i]);//学生作业中的可变内容
}
}
}
}

Console.ReadKey();
}
}
}


出现过的错误:经常下意识的认为索引从1开始
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: