Design Pattern Examples
Overview of object-oriented design patterns
Interpreter_Class.cs
Go to the documentation of this file.
1
5
6using System;
7using System.Globalization;
8using System.Text;
9using System.Threading;
10
12{
13
32 {
33 const int PERIOD = 100;
34 const int QUESTION = 101;
35
40 static string[] _commonwords = new string[]
41 {
42 "the",
43 "be",
44 "to",
45 "of",
46 "and",
47 "a",
48 "in",
49 "that",
50 "have",
51 "I",
52 "it",
53 "for",
54 "not",
55 "on",
56 "with",
57 "he",
58 "as",
59 "you",
60 "do",
61 "at",
62 "this",
63 "but",
64 "his",
65 "by",
66 "from",
67 "they",
68 "we",
69 "say",
70 "her",
71 "she",
72 "or",
73 "an",
74 "will",
75 "my",
76 "one",
77 "all",
78 "would",
79 "there",
80 "their",
81 "what",
82 };
83
84
93 string _InterpretToken(int token)
94 {
95 string tokenAsString = "";
96
97 // Rule 1: token is between 0 and the number of common words.
98 if (token >= 0 && token < _commonwords.Length)
99 {
100 tokenAsString = _commonwords[token];
101 }
102 else
103 {
104 // Rule 1: token can also be a PERIOD
105 if (token == PERIOD)
106 {
107 tokenAsString = ".";
108 }
109 // Rule 1: or the token can also be a QUESTION
110 else if (token == QUESTION)
111 {
112 tokenAsString = "?";
113 }
114 else
115 {
116 // Rule 1: Invalid tokens returned in a string.
117 tokenAsString = String.Format("<UNKNOWN TOKEN {0}>", token);
118 }
119 }
120 return tokenAsString;
121 }
122
123
131 public string Interpret(int[] tokens)
132 {
133 StringBuilder output = new StringBuilder();
134
135 CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
136 TextInfo textInfo = cultureInfo.TextInfo;
137
138 int numTokens = tokens.Length;
139
140 for (int tokenIndex = 0; tokenIndex < numTokens; ++tokenIndex)
141 {
142 // Rule 1: Interpret token
143 string tokenAsString = _InterpretToken(tokens[tokenIndex]);
144 if (tokenIndex == 0)
145 {
146 // Rule 2: First word in sentence gets capitalized according to local rules.
147 tokenAsString = textInfo.ToTitleCase(tokenAsString);
148 }
149 output.Append(tokenAsString);
150
151 // Rule 4: No space between last two tokens (if the following expression is false)
152 if (tokenIndex + 2 < numTokens)
153 {
154 // Rule 3: Separate all words by a single space.
155 output.Append(" ");
156 }
157 }
158
159 return output.ToString();
160 }
161 }
162}
Representation of a simple interpreter.
static string[] _commonwords
The 40 most common words in English (in order but that doesn't really matter here)....
string _InterpretToken(int token)
Helper method to convert the token into its corresponding word or punctuation mark.
string Interpret(int[] tokens)
Given an array of integer tokens, convert the tokens into a single string of space-delimited words,...
The namespace containing all Design Pattern Examples implemented in C#.