Start a new line with spaces

I am stuck with this problem, I would really appreciate if someone can help me solve this problem.

  • I want to add spaces for a subfolder, like this format below (this should be done with recursion)
  • I want to add spaces for a subfolder, like this format below. (it should be done with recursion)

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace G14_211115 { class Program { static void Main(string[] args) { string path = @"C:\Program Files\FinchVPN"; WriteDirectories(path); Console.ReadKey(); } /* Tasks. * 1. I want to add spaces for subfolder like this format down below. ( it must be done with recursion) * Like this * -------------------------------------------------------------- * Folder 1 * Folder 1.1 * Folder 1.2 * Folder 2 * Folder 2.1 * Folder 2.1.1 * Folder 2.2 * Folder 3 * Folder 4 * * 2. Task 2 I want to retype this code without using recurrence and C# inbuilt functions. */ static void WriteDirectories(string path) { string[] dirs = Directory.GetDirectories(path); for(int i = 0; i < dirs.Length; i++) { Console.WriteLine(dirs[i]); WriteDirectories(dirs[i]); } } } } 
+5
source share
2 answers

When you call WriteDirectories recursively, you can pass a variable to each call denoting a (recursion)level . Using this, you can simply put spaces before exiting.

Therefore, you will need to change your code as follows:

 static void WriteDirectories(string path, int level = 0) { string[] dirs = Directory.GetDirectories(path); for (int i = 0; i < dirs.Length; i++) { for (int j = 0; j < level; j++) { Console.Write(" "); } Console.WriteLine(dirs[i]); WriteDirectories(dirs[i], (level + 1)); } } 

If you need more than one place per level, you can just change the inner loop, j < 2 * level will give you 2 spaces per level, etc.

Update (thanks to David)

Instead of an inner loop, you can use new string(' ', level) to create a new string containing the specified level -times character.

Thus, the internal for -loop will be replaced by Console.Write(new string(' ', level)); .

+6
source

just specify the depth parameter for your recursive call and add spaces according to the depth.

  static void WriteDirectories(string path, int depth) { string[] dirs = Directory.GetDirectories(path); for(int i = 0; i < dirs.Length; i++) { string preSpaces = new String(' ',depth); Console.WriteLine(preSpaces + dirs[i]); WriteDirectories(dirs[i], depth+1); } } 

Your first call should contain 0 or 1 as depth.

0
source

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


All Articles