Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having difficulty interpreting debugger with StringBuilder in C#

When I debug this console application, it's giving a strange result. There's obviously something I'm overlooking.

class Program
{
    static void Main(string[] args)
    {
        int ops = int.Parse(Console.ReadLine());           
        int inte = 0;
        StringBuilder roll = new StringBuilder();

        Operations(roll, inte, ops);
    }

    static void Operations(StringBuilder roll, int inte, int ops)
    {
        for (int i = 0; i < ops; i++)
        {
            roll.AppendLine(Console.ReadLine()); 

            inte = roll.ToString().IndexOf("^");

            if (inte == i)
                roll.Remove(i, 1);


            if (roll.ToString().IndexOf("!") == i)
                roll.Remove(i, 1);              
        }

        Console.WriteLine(roll.ToString());
        Console.ReadLine();
    }
}

For inputs, type in "3" for the first input (integer "inte"), and "^A", "^B" "^D" for the other 3 ReadLine entries. On the first iteration of the loop, it will remove the ^ as expected. But on the second iteration (i =1), it reads inte as 3. But it should be 1, because on the second round the Stringbuilder has appended "^B" to A, so it's now "A^B". I'm trying to remove the "^"s (and "!"s too) when they're entered as the stringbuilder is appending the strings. Why is the "inte" integer reading 3 on the second round?

like image 792
flimflam57 Avatar asked Feb 15 '23 07:02

flimflam57


1 Answers

This is your problem:

roll.AppendLine(Console.ReadLine());

You're using AppendLine, so on the first iteration it's appending "^A" and then a carriage return ('\r') and line feed ('\n'). After removing the first character, you've still got 3 characters in the string. ('A', '\r' and '\n'). That's why after appending ^B\r\n" in the second iteration, you find the^` at index 3 rather than index 1.

Just change it to:

roll.Append(Console.ReadLine());

and I suspect you'll get the results you're expecting.

like image 70
Jon Skeet Avatar answered Feb 17 '23 21:02

Jon Skeet