Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building a new path-like string from an existing one

Tags:

string

c#

.net

I'd like to modify a source string which is looking like

"one.two.three" 

and transfer it into a string with slashes to use it as a folder string which has the following structure:

"one\one.two\one.two.three"

Do you know more elegant ways to realize this, than my solution below? I'm not very satisfied with my for-loops.

var folder = "one.two.three";
var folderParts = folder.Split('.');
var newFolder = new StringBuilder();
for (int i = 0; i < folderParts.Length; i++)
{
    for (int j = 0; j < i; j++)
    {
       if (j == 0)
       {
          newFolder.Append("\\");
       }

       newFolder.Append($"{folderParts[j]}.");
    }

    newFolder.Append(folderParts[i]);
}
like image 282
Christoph Brückmann Avatar asked Mar 22 '19 08:03

Christoph Brückmann


Video Answer


2 Answers

You can do this quite tersely with Regex

var newFolder = Regex.Replace(folder, @"\.", @"\$`.");

This matches on each period. Each time it finds a period, it inserts a backslash and then the entire input string before the match ($`). We have to add the period in again at the end.

So, steps are (< and > indicate text inserted by the substitution at that step):

  1. Match on the 1st period. one<\one>.two.three
  2. Match on the 2nd period. one\one.two<\one.two>.three
  3. Result: one\one.two\one.two.three

For bonus points, use Path.DirectorySeparatorChar for cross-platform correctness.

var newFolder = Regex.Replace(folder, @"\.", $"{Path.DirectorySeparatorChar}$`.")

Here's another linqy way:

var a = "";
var newFolder = Path.Combine(folder.Split('.')
    .Select(x => a += (a == "" ? "" : ".") + x).ToArray());
like image 101
canton7 Avatar answered Sep 24 '22 23:09

canton7


You can try Linq:

  string folder = "one.two.three";
  string[] parts = folder.Split('.');

  string result = Path.Combine(Enumerable
    .Range(1, parts.Length)
    .Select(i => string.Join(".", parts.Take(i)))
    .ToArray());

  Console.Write(newFolder);

Outcome:

 one\one.two\one.two.three 
like image 45
Dmitry Bychenko Avatar answered Sep 21 '22 23:09

Dmitry Bychenko