I am trying to get better in C# and so I thought making a simple programming language that can run basic commands like println("Hi");
and print("Hi");
However, the code shown scans for one foreach() value, my C# code:
string text = File.ReadAllText(inputFile);
string[] fileText = text.Split(";");
foreach (string token in fileText) {
if (token.StartsWith("println(") && token.EndsWith(")")) {
if (token.Split("\"").Length == 3) {
Console.WriteLine(token.Split("\"")[1]);
} else {
throw new Exception($"println(string); takes exactly 3 arguments of which {token.Split("\"").Length} were given.");
}
} else if (token.StartsWith("println(")) {
throw new Exception("Syntax error");
} else if (token.StartsWith("print(") && token.EndsWith(")")) {
if (token.Split("\"").Length == 3) {
Console.Write(token.Split("\"")[1]);
} else {
throw new Exception(($"print(string); takes exactly 3 arguments of which {token.Split("\"").Length} were given."));
}
} else if (token.StartsWith("print(")) {
throw new Exception("Syntax error");
}
}
My testing file:
print("This ");
println("is a test.");
I only get This
as output.
CodePudding user response:
You have stated in a comment (now in the question proper) that text
is populated with:
string text = File.ReadAllText(inputFile);
That means a split based on semi-colons will give you the following strings (though the third depends on what comes after the final semi-colon):
print("This ")
<newline>println("is a test.")
<possibly-newline-but-irrelevant-for-this-question>
In other words, that second one does not start with println(
, which is why your code is not picking it up. You may want to rethink how you're handling that, especially if you want to handle indented code as well.
I'd (at least initially) opt for stripping all white-space from the beginning and end of token
before doing any comparisons.
CodePudding user response:
What @paxdiablo said but the following will also work for the input shown:
var lines = File.ReadAllLines(inputFile); // ReadAllLines, not ReadAllText
foreach (string line in lines) {
var token = line.TrimEnd(new []{';'});
// your code here