/* * Aresh Saharkhiz * saharkiz@gmail.com * Associate Professor / Mapua Institute of Technology / Philippines */ using System; using System.IO; // Introduction to Software Testing // Authors: Paul Ammann & Jeff Offutt // Chapter 2, section 2.3, page 62 /// /// ***************************************************** /// Rewraps the string (Similar to the Unix fmt). /// Given a string S, eliminate existing CRs and add CRs to the /// closest spaces before column N. Two CRs in a row are considered to /// be "hard CRs" and are left alone. /// ********************************************************* /// internal class fmtRewrap_class { internal const char CR = '\n'; internal const int inWord = 0; internal const int betweenWord = 1; internal const int lineBreak = 2; internal const int crFound = 3; private static string fmtRewrap(string S, int N) { int state = betweenWord; int lastSpace = -1; int col = 1; int i = 0; char c; char[] SArr = S.ToCharArray(); while (i < S.Length) { c = SArr[i]; col++; if (col >= N) { state = lineBreak; } else if (c == CR) { state = crFound; } else if (c == ' ') { state = betweenWord; } else { state = inWord; } switch (state) { case betweenWord: lastSpace = i; break; case lineBreak: SArr[lastSpace] = CR; col = i - lastSpace; break; case crFound: if (i + 1 < S.Length && SArr[i + 1] == CR) { i++; // Two CRs => hard return col = 1; } else { SArr[i] = ' '; } break; case inWord: default: break; } // end switch i++; } // end while S = new string(SArr) + CR; return (S); } public static void Main(string[] argv) { // Driver method for fmtRewrap // Read an array and an integer from standard input, call fmtRewrap() int integer = 0; int[] inArr = new int[argv.Length]; if (argv.Length != 1) { Console.WriteLine("Usage: java fmtRewrap v1 "); return; } Console.WriteLine("Enter an integer: "); integer = N; Console.WriteLine("The Result String is: " + fmtRewrap(argv[0], integer)); } // ==================================== // Read (or choose) an integer private static int N { get { int inputInt = 1; //BufferedReader @in = new BufferedReader(new InputStreamReader(System.in)); string inStr; try { inStr = Console.ReadLine(); inputInt = Convert.ToInt32(inStr); } catch (IOException) { Console.WriteLine("Could not read input, choosing 1."); } catch (FormatException) { Console.WriteLine("Entry must be a number, choosing 1."); } return (inputInt); } } // end getN }