/* * Aresh Saharkhiz * saharkiz@gmail.com * Associate Professor / Mapua Institute of Technology / Philippines */ using System; // Introduction to Software Testing // Authors: Paul Ammann & Jeff Offutt // Chapter 2, section 2.3, page 56 internal class TestPat { public static void Main(string[] argv) { const int MAX = 100; char[] subject = new char[MAX]; char[] pattern = new char[MAX]; if (argv.Length != 2) { Console.WriteLine("java TestPat String-Subject String-Pattern"); return; } subject = argv[0].ToCharArray(); pattern = argv[1].ToCharArray(); TestPat testPat = new TestPat(); int n = 0; if ((n = testPat.pat(subject, pattern)) == -1) { Console.WriteLine("Pattern string is not a substring of the subject string"); } else { Console.WriteLine("Pattern string begins at the character " + n); } } public TestPat() { } public virtual int pat(char[] subject, char[] pattern) { // Post: if pattern is not a substring of subject, return -1 // else return (zero-based) index where the pattern (first) // starts in subject const int NOTFOUND = -1; int iSub = 0, rtnIndex = NOTFOUND; bool isPat = false; int subjectLen = subject.Length; int patternLen = pattern.Length; while (isPat == false && iSub + patternLen - 1 < subjectLen) { if (subject[iSub] == pattern[0]) { rtnIndex = iSub; // Starting at zero isPat = true; for (int iPat = 1; iPat < patternLen; iPat++) { if (subject[iSub + iPat] != pattern[iPat]) { rtnIndex = NOTFOUND; isPat = false; break; // out of for loop } } } iSub++; } return (rtnIndex); } }