foreach(string token in text.Split(";")) scans only for one value

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) {

                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) {

                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.

>Solution :

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.")

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.

Leave a Reply