Exercise 2 Create a Translator Class
In this exercise, you will create a Friend class to contain the logic and data that the Translator application uses.
To create a class
1. From the Project menu, choose Add Class. Visual Studio displays the Add New Item dialog box. Name the class TranslatorClass.vb and click Open.
2. In the code window, add the following code:
Visual Basic .NET
Friend Class TranslatorClass
Private mstrText As String Private mstrOriginal As String
' Controls access to the module-level ' variables.
Public Property Text() As String Get
Text = mstrText End Get
Set(ByVal Value As String) mstrText = Value
' Keep a copy of the original for Restore. mstrOriginal = Value End Set End Property
' Restores translated text back to the original. Public Sub Restore()
mstrText = mstrOriginal End Sub
' Translates the value in the Text property. Public Sub Translated
Dim strWord As String, intCount As Integer Dim arrWords() As String Dim bCaps As Boolean
' Convert the string to an array using System.String. arrWords = mstrText.Split(" ") For intCount = 0 To UBound(arrWords) ' Check if word is capitalized.
If LCase(arrWords(intCount)) <> arrWords(intCount) Then bCaps = True arrWords(intCount) = LCase(arrWords(intCount)) End If strWord = arrWords(intCount) ' Do translation.
If strWord <> "" Then strWord = Right(strWord, Len(strWord) -1)&_
Left(strWord, 1) & "ay" ' Recapitalize if necessary If bCaps Then strWord = UCase(Left(strWord, 1)) &_ Right(strWord, Len(strWord) - 1)
End If End If
' Store back in the array. arrWords(intCount) = strWord ' Reset caps flag. bCaps = False
Next
' Rebuild string from array. mstrText = String.Join(" ", arrWords) End Sub
End Class
Visual C#
internal class TranslatorClass {
string mstrText, mstrOriginal;
// Controls access to class-level variables.
public string Text {
return mstrText;
mstrText = value;
// Keep a copy of the original for Restore. mstrOriginal = value;
// Restores translated text back to the original.
public void Restore() {
mstrText = mstrOriginal;
// Translates the value in the Text property.
public void Translate() {
string strWord; string[] arrWords; bool bCaps = false;
// Convert the string into an array using System.String. arrWords = mstrText.Split(' ');
for(int intCount = 0; intCount <= arrWords.GetUpperBound(0);
// Change to lowercase.
strWord = arrWords[intCount].ToLower(); // Check if word is capitalized.
if(!arrWords[intCount].Equals(strWord)) bCaps = true; // Do translation.
strWord = strWord.Substring(1,strWord.Length -1) +
strWord.Substring(0,1) + "ay"; // Recapitalize if necessary. if(bCaps)
strWord = strWord.Substring(0,1).ToUpper() + strWord.Substring(1, strWord.Length - 1);
// Store the word back in the array. arrWords[intCount] = strWord; // Reset the caps flag. bCaps = false;
// Rebuild the string from the array. mstrText = String.Join(" ", arrWords);
Post a comment