標籤:
老師給小學生門布置了一些作業,讓它們按照一個模版寫一些字串交上來,同學們把作業交上來了,問題來了,這麼多的作業老師批改不過來,現在請你幫老師寫一個程式,協助老師確定各個字串是否合格。首先老師有一個匹配模版,比如是“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 Program10 {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開始
C#字串題目