Having difficulty interpreting the debugger using StringBuilder in C #

When I debug this console application, it gives a strange result. Obviously something that I don’t notice.

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(); } } 

To enter, enter "3" for the first input (integer "inte") and "^ A", "^ B" "^ D" for the remaining 3 ReadLine entries. At the first iteration of the loop, it will remove ^ as expected. But in the second iteration (i = 1) it reads inte as 3. But it should be 1, because in the second round Stringbuilder adds β€œ^ B” to A, so now it is β€œA ^ B". I try to remove the "^" (and "!"), Too, when they are entered, when the string block adds strings. Why is "inte" an integer reading of 3 in the second round?

+4
source share
1 answer

It's your problem:

 roll.AppendLine(Console.ReadLine()); 

You are using AppendLine , so in the first iteration, add "^ A" and then carriage return ( '\r' ) and line feed ( '\n' ). After deleting the first character, you still have 3 characters per line. ( 'A' , '\r' and '\n' ). That's why after adding ^B\r\n" in the second iteration, you find the ^` to index 3 instead of index 1.

Just change it to:

 roll.Append(Console.ReadLine()); 

and I suspect you will get the expected results.

+8
source

Source: https://habr.com/ru/post/1502066/


All Articles