Exercise
C# to Pascal converter
Objetive
Create a program that converts simple C# programs, such as the following one, to the Pascal language.
Example Code
// Importing the System namespace to use basic functionality like Regex
using System;
class Program // Class definition in C#
{
// Main method where the program execution begins
static void Main()
{
// Example C# code to convert
string cSharpCode = @"
using System;
class Program
{
static void Main()
{
int x = 10;
int y = 5;
if (x > y)
{
Console.WriteLine(""x is greater"");
}
else
{
Console.WriteLine(""y is greater"");
}
}
}
";
// Convert the C# code to Pascal
string pascalCode = ConvertCSharpToPascal(cSharpCode);
// Print the Pascal code to the console
Console.WriteLine("Converted Pascal Code:");
Console.WriteLine(pascalCode);
}
// Method to convert simple C# code to Pascal code
static string ConvertCSharpToPascal(string cSharpCode)
{
// Remove 'using System;' line from C#
// This line removes the unnecessary 'using System;' from the C# code
cSharpCode = Regex.Replace(cSharpCode, @"using\s+System;\s*", "");
// Convert C# class declaration to Pascal program declaration
// This converts the C# 'class Program' to Pascal's 'program Program;'
cSharpCode = Regex.Replace(cSharpCode, @"class\s+(\w+)", "program $1;");
// Convert C# method declaration to Pascal method declaration
// This converts the C# 'static void Main()' to Pascal's 'begin'
cSharpCode = Regex.Replace(cSharpCode, @"static\s+void\s+Main\(\)", "begin");
// Convert C# variables declaration to Pascal variable declaration
// This converts C# declarations like 'int x = 10;' to Pascal's 'var x: Integer; begin x := 10;'
cSharpCode = Regex.Replace(cSharpCode, @"int\s+(\w+)\s*=\s*(\d+);", "var $1: Integer; begin $1 := $2;");
// Convert C# if-else block to Pascal if-else block
// This converts C# 'if (condition) { ... } else { ... }' to Pascal's 'if condition then ... else ...'
cSharpCode = Regex.Replace(cSharpCode, @"if\s*\((.*?)\)\s*{(.*?)}\s*else\s*{(.*?)}", "if $1 then\n$2\nelse\n$3");
// Convert C# method calls like Console.WriteLine to Pascal WriteLn
// This converts the C# method 'Console.WriteLine()' to Pascal's 'WriteLn()'
cSharpCode = Regex.Replace(cSharpCode, @"Console\.WriteLine\((.*?)\);", "WriteLn($1);");
// Add an 'end.' to complete the Pascal program
// This adds 'end.' at the end of the Pascal code to indicate the end of the program
cSharpCode = cSharpCode + "\nend.";
// Return the final Pascal code
return cSharpCode;
}
}