Answer to Exercise 9

The solution here is to use Substring and PadLeft in a loop. You grab one character at a time from the word and add spaces to the start of the character. The answer is more complicated in Java because it doesn't have an inbuilt Pad method. There are various ways to add your own pad method. The one we've went for uses String.format.

 

C# NET Answer

private void btnDiagonal_Click(object sender, EventArgs e)
{
	string diag = "DIAGONALLY";

	for (int i = 0; i < diag.Length; i++)
	{            
	    string pad = diag.Substring(i, 1);
	    
	    listBox1.Items.Add(pad.PadLeft(i + 1));
	}
}

 

VB NET Answer

Private Sub btnDiagonal_Click(sender As Object, e As EventArgs) Handles btnDiagonal.Click

	Dim diag As String = "DIAGONALLY"

	For i = 0 To diag.Length - 1
		Dim pad As String = diag.Substring(i, 1)
		ListBox1.Items.Add(pad.PadLeft(i + 1))
	Next

End Sub

 

Java Answer

public static void main(String[] args) {

    String diag = "DIAGONALLY";
    String pad = "";

    for (int i = 0; i < diag.length(); i++)
    {
        pad = diag.substring(i, i + 1);
        pad = padLeft(pad, i + 1);

        System.out.println(pad);     
    }
}

public static String padLeft(String str, int position) {
    return String.format("%1$" + position + "s", str);  
}