Using a nested for loop and getting unexpected repetitions in c#

I've the following code in c# visual basic 2010:

for (int i = 7; i > 0; i--)
{
    Char star = '*';
    string numbers = "765432" ;

    //Console.WriteLine(star);

    for (int a = 0; a < i; a++)
    {
        Console.Write(star);
    }
    for (int b =  0; b < i; b++)
    {
        numbers.TrimEnd(numbers[numbers.Length - 1]);
        Console.Write(numbers);
    }
    Console.WriteLine();   
}
Console.ReadLine();   

I was expecting the outcome: *765432 repeated on the screen 7 times, instead I get:

*****765432765432765432765432765432

****765432765432765432765432

***765432765432765432

**765432765432

*765432

(I can't display the full outcome because it doesn't come back properly on screen but it's basically the variables star and numbers displayed 7 times on line 1, 6 times on line 2 etc. until once in line 7)

My understanding is that the a and b variables declared in the for loops should dictate how many times the for loop is entered into, why are the star and numbers variables also being written 7 times then 6 times to match the number of times the loop is entered into? Especially when they are initialised as * and 765432?

Jon Skeet
people
quotationmark

This is the problem (I suspect, anyway - it's certainly a problem):

numbers.TrimEnd(numbers[numbers.Length - 1]);

Strings are immutable in .NET. TrimEnd doesn't change the existing string - it returns a reference to a new one. As highlighted in the documentation:

This method does not modify the value of the current instance. Instead, it returns a new string in which all trailing characters found in trimChars are removed from the current string.

You'd also be better off using Substring for simplicity to "remove" the last character:

numbers = numbers.Substring(0, numbers.Length - 1);

Or indeed Remove:

numbers = numbers.Remove(numbers.Length - 1);

... although this will actually fail on the 7th iteration as the string will be empty at this point. It's not really what you were trying to achieve, but I think you need to take a step back from it and think carefully about each step in the process.

people

See more on this question at Stackoverflow