从现有的字符串构建新的类似路径的字符串

Chr*_*ann 6 .net c# string

我想修改看起来像的源字符串

"one.two.three" 
Run Code Online (Sandbox Code Playgroud)

并将其转换为带斜杠的字符串,以将其用作具有以下结构的文件夹字符串:

"one\one.two\one.two.three"
Run Code Online (Sandbox Code Playgroud)

与下面的解决方案相比,您知道更优雅的方法吗?我对for循环不是很满意。

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]);
}
Run Code Online (Sandbox Code Playgroud)

can*_*on7 9

您可以使用Regex非常简洁地执行此操作

var newFolder = Regex.Replace(folder, @"\.", @"\$`.");
Run Code Online (Sandbox Code Playgroud)

这在每个期间都匹配。每次找到句点时,都会插入一个反斜杠,然后在匹配($`)之前插入整个输入字符串。我们必须在末尾再次添加句点。

因此,步骤为(<和>表示在该步骤由替换插入的文本):

  1. 第一场比赛。 one<\one>.two.three
  2. 第二节比赛。 one\one.two<\one.two>.three
  3. 结果: one\one.two\one.two.three

对于加分,请使用Path.DirectorySeparatorChar跨平台正确性。

var newFolder = Regex.Replace(folder, @"\.", $"{Path.DirectorySeparatorChar}$`.")
Run Code Online (Sandbox Code Playgroud)

这是另一种linqy方式:

var a = "";
var newFolder = Path.Combine(folder.Split('.')
    .Select(x => a += (a == "" ? "" : ".") + x).ToArray());
Run Code Online (Sandbox Code Playgroud)


Dmi*_*nko 8

您可以尝试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);
Run Code Online (Sandbox Code Playgroud)

结果:

 one\one.two\one.two.three 
Run Code Online (Sandbox Code Playgroud)