Building a new path-like string from an existing one Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) The Ask Question Wizard is Live! Data science time! April 2019 and salary with experience Should we burninate the [wrap] tag?How to create a new object instance from a TypeWhat's the best way to build a string of delimited items in Java?How do you get a string from a MemoryStream?How to get relative path from absolute pathHow do I create a Java string from the contents of a file?How to get the filename without the extension from a path in Python?How do I trim whitespace from a Python string?Creating a comma separated list from IList<string> or IEnumerable<string>How do I generate a stream from a string?Why not inherit from List<T>?

List *all* the tuples!

Does accepting a pardon have any bearing on trying that person for the same crime in a sovereign jurisdiction?

Is the Standard Deduction better than Itemized when both are the same amount?

How do I stop a creek from eroding my steep embankment?

What is this single-engine low-wing propeller plane?

Does surprise arrest existing movement?

do i need a schengen visa for a direct flight to amsterdam?

What does the "x" in "x86" represent?

When -s is used with third person singular. What's its use in this context?

Determinant is linear as a function of each of the rows of the matrix.

Check which numbers satisfy the condition [A*B*C = A! + B! + C!]

ListPlot join points by nearest neighbor rather than order

Withdrew £2800, but only £2000 shows as withdrawn on online banking; what are my obligations?

How can I fade player when goes inside or outside of the area?

How to do this path/lattice with tikz

How to recreate this effect in Photoshop?

What would be the ideal power source for a cybernetic eye?

Gastric acid as a weapon

Right-skewed distribution with mean equals to mode?

Single word antonym of "flightless"

If 'B is more likely given A', then 'A is more likely given B'

Why is black pepper both grey and black?

Were Kohanim forbidden from serving in King David's army?

What does '1 unit of lemon juice' mean in a grandma's drink recipe?



Building a new path-like string from an existing one



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
The Ask Question Wizard is Live!
Data science time! April 2019 and salary with experience
Should we burninate the [wrap] tag?How to create a new object instance from a TypeWhat's the best way to build a string of delimited items in Java?How do you get a string from a MemoryStream?How to get relative path from absolute pathHow do I create a Java string from the contents of a file?How to get the filename without the extension from a path in Python?How do I trim whitespace from a Python string?Creating a comma separated list from IList<string> or IEnumerable<string>How do I generate a stream from a string?Why not inherit from List<T>?



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








6















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:



"oneone.twoone.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]);










share|improve this question



















  • 1





    There's got to be a way to do this with Aggregate, but I can't quite put my finger on it.

    – canton7
    Mar 22 at 15:38

















6















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:



"oneone.twoone.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]);










share|improve this question



















  • 1





    There's got to be a way to do this with Aggregate, but I can't quite put my finger on it.

    – canton7
    Mar 22 at 15:38













6












6








6


1






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:



"oneone.twoone.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]);










share|improve this question
















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:



"oneone.twoone.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]);







c# .net string






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 22 at 15:39









vaxquis

7,86253958




7,86253958










asked Mar 22 at 8:26









Christoph BrückmannChristoph Brückmann

1,12311939




1,12311939







  • 1





    There's got to be a way to do this with Aggregate, but I can't quite put my finger on it.

    – canton7
    Mar 22 at 15:38












  • 1





    There's got to be a way to do this with Aggregate, but I can't quite put my finger on it.

    – canton7
    Mar 22 at 15:38







1




1





There's got to be a way to do this with Aggregate, but I can't quite put my finger on it.

– canton7
Mar 22 at 15:38





There's got to be a way to do this with Aggregate, but I can't quite put my finger on it.

– canton7
Mar 22 at 15:38












4 Answers
4






active

oldest

votes


















9














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. oneone.two<one.two>.three

  3. Result: oneone.twoone.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());





share|improve this answer

























  • Nice! Just on Replace to get the result

    – Dmitry Bychenko
    Mar 22 at 8:44











  • That is, of course, the shortest solution but pretty hard to read if you're not a regex geek. Thank you for the detailed explanation! :)

    – Christoph Brückmann
    Mar 22 at 8:54












  • Also thank you for the hint regarding cross-platform compatibility.

    – Christoph Brückmann
    Mar 22 at 9:01






  • 1





    @Christoph Agreed. I said it was terse, not that it was necessarily readable! To be honest, I'd write a comment against any of these solutions saying what it did. You can add a few extra lines of comments to this one explaining how it works before it gets as long as the next tersest answer.

    – canton7
    Mar 22 at 9:37


















8














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:



 oneone.twoone.two.three 





share|improve this answer




















  • 1





    Perhaps use Path.Combine over that first string.Join, for cross-platform?

    – canton7
    Mar 22 at 8:41











  • @canton7: Thank you! Path.Combine is much better in the context

    – Dmitry Bychenko
    Mar 22 at 8:44











  • Also a very nice solution. More readable for me. :)

    – Christoph Brückmann
    Mar 22 at 8:58











  • I think this definitely wins the prize for readability

    – canton7
    Mar 22 at 9:40


















3














You can go forward-only in one loop like this:



 var folder = "one.two.three";
var newFolder = new StringBuilder();

int index = -1;
while (index + 1 < folder.Length)
index = folder.IndexOf('.', index + 1);
if (index < 0)
newFolder.Append(folder);
break;

else
newFolder.Append(folder, 0, index);
newFolder.Append(Path.DirectorySeparatorChar);




You can try it out here.






share|improve this answer
































    3














    Instead of splitting the string first, I find it more elegant to start with what you have and reduce it:



    var folder = "one.two.three";
    var newFolder = string.Empty;
    for (var f = folder; f.Any(); f = f.Remove(Math.Max(f.LastIndexOf('.'), 0)))
    newFolder = Path.Combine(f, newFolder);

    Console.WriteLine(newFolder);


    Output:



    oneone.twoone.two.three 





    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55295571%2fbuilding-a-new-path-like-string-from-an-existing-one%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      4 Answers
      4






      active

      oldest

      votes








      4 Answers
      4






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      9














      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. oneone.two<one.two>.three

      3. Result: oneone.twoone.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());





      share|improve this answer

























      • Nice! Just on Replace to get the result

        – Dmitry Bychenko
        Mar 22 at 8:44











      • That is, of course, the shortest solution but pretty hard to read if you're not a regex geek. Thank you for the detailed explanation! :)

        – Christoph Brückmann
        Mar 22 at 8:54












      • Also thank you for the hint regarding cross-platform compatibility.

        – Christoph Brückmann
        Mar 22 at 9:01






      • 1





        @Christoph Agreed. I said it was terse, not that it was necessarily readable! To be honest, I'd write a comment against any of these solutions saying what it did. You can add a few extra lines of comments to this one explaining how it works before it gets as long as the next tersest answer.

        – canton7
        Mar 22 at 9:37















      9














      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. oneone.two<one.two>.three

      3. Result: oneone.twoone.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());





      share|improve this answer

























      • Nice! Just on Replace to get the result

        – Dmitry Bychenko
        Mar 22 at 8:44











      • That is, of course, the shortest solution but pretty hard to read if you're not a regex geek. Thank you for the detailed explanation! :)

        – Christoph Brückmann
        Mar 22 at 8:54












      • Also thank you for the hint regarding cross-platform compatibility.

        – Christoph Brückmann
        Mar 22 at 9:01






      • 1





        @Christoph Agreed. I said it was terse, not that it was necessarily readable! To be honest, I'd write a comment against any of these solutions saying what it did. You can add a few extra lines of comments to this one explaining how it works before it gets as long as the next tersest answer.

        – canton7
        Mar 22 at 9:37













      9












      9








      9







      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. oneone.two<one.two>.three

      3. Result: oneone.twoone.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());





      share|improve this answer















      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. oneone.two<one.two>.three

      3. Result: oneone.twoone.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());






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Mar 22 at 22:28

























      answered Mar 22 at 8:33









      canton7canton7

      6,1231729




      6,1231729












      • Nice! Just on Replace to get the result

        – Dmitry Bychenko
        Mar 22 at 8:44











      • That is, of course, the shortest solution but pretty hard to read if you're not a regex geek. Thank you for the detailed explanation! :)

        – Christoph Brückmann
        Mar 22 at 8:54












      • Also thank you for the hint regarding cross-platform compatibility.

        – Christoph Brückmann
        Mar 22 at 9:01






      • 1





        @Christoph Agreed. I said it was terse, not that it was necessarily readable! To be honest, I'd write a comment against any of these solutions saying what it did. You can add a few extra lines of comments to this one explaining how it works before it gets as long as the next tersest answer.

        – canton7
        Mar 22 at 9:37

















      • Nice! Just on Replace to get the result

        – Dmitry Bychenko
        Mar 22 at 8:44











      • That is, of course, the shortest solution but pretty hard to read if you're not a regex geek. Thank you for the detailed explanation! :)

        – Christoph Brückmann
        Mar 22 at 8:54












      • Also thank you for the hint regarding cross-platform compatibility.

        – Christoph Brückmann
        Mar 22 at 9:01






      • 1





        @Christoph Agreed. I said it was terse, not that it was necessarily readable! To be honest, I'd write a comment against any of these solutions saying what it did. You can add a few extra lines of comments to this one explaining how it works before it gets as long as the next tersest answer.

        – canton7
        Mar 22 at 9:37
















      Nice! Just on Replace to get the result

      – Dmitry Bychenko
      Mar 22 at 8:44





      Nice! Just on Replace to get the result

      – Dmitry Bychenko
      Mar 22 at 8:44













      That is, of course, the shortest solution but pretty hard to read if you're not a regex geek. Thank you for the detailed explanation! :)

      – Christoph Brückmann
      Mar 22 at 8:54






      That is, of course, the shortest solution but pretty hard to read if you're not a regex geek. Thank you for the detailed explanation! :)

      – Christoph Brückmann
      Mar 22 at 8:54














      Also thank you for the hint regarding cross-platform compatibility.

      – Christoph Brückmann
      Mar 22 at 9:01





      Also thank you for the hint regarding cross-platform compatibility.

      – Christoph Brückmann
      Mar 22 at 9:01




      1




      1





      @Christoph Agreed. I said it was terse, not that it was necessarily readable! To be honest, I'd write a comment against any of these solutions saying what it did. You can add a few extra lines of comments to this one explaining how it works before it gets as long as the next tersest answer.

      – canton7
      Mar 22 at 9:37





      @Christoph Agreed. I said it was terse, not that it was necessarily readable! To be honest, I'd write a comment against any of these solutions saying what it did. You can add a few extra lines of comments to this one explaining how it works before it gets as long as the next tersest answer.

      – canton7
      Mar 22 at 9:37













      8














      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:



       oneone.twoone.two.three 





      share|improve this answer




















      • 1





        Perhaps use Path.Combine over that first string.Join, for cross-platform?

        – canton7
        Mar 22 at 8:41











      • @canton7: Thank you! Path.Combine is much better in the context

        – Dmitry Bychenko
        Mar 22 at 8:44











      • Also a very nice solution. More readable for me. :)

        – Christoph Brückmann
        Mar 22 at 8:58











      • I think this definitely wins the prize for readability

        – canton7
        Mar 22 at 9:40















      8














      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:



       oneone.twoone.two.three 





      share|improve this answer




















      • 1





        Perhaps use Path.Combine over that first string.Join, for cross-platform?

        – canton7
        Mar 22 at 8:41











      • @canton7: Thank you! Path.Combine is much better in the context

        – Dmitry Bychenko
        Mar 22 at 8:44











      • Also a very nice solution. More readable for me. :)

        – Christoph Brückmann
        Mar 22 at 8:58











      • I think this definitely wins the prize for readability

        – canton7
        Mar 22 at 9:40













      8












      8








      8







      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:



       oneone.twoone.two.three 





      share|improve this answer















      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:



       oneone.twoone.two.three 






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Mar 22 at 8:43

























      answered Mar 22 at 8:31









      Dmitry BychenkoDmitry Bychenko

      112k1099142




      112k1099142







      • 1





        Perhaps use Path.Combine over that first string.Join, for cross-platform?

        – canton7
        Mar 22 at 8:41











      • @canton7: Thank you! Path.Combine is much better in the context

        – Dmitry Bychenko
        Mar 22 at 8:44











      • Also a very nice solution. More readable for me. :)

        – Christoph Brückmann
        Mar 22 at 8:58











      • I think this definitely wins the prize for readability

        – canton7
        Mar 22 at 9:40












      • 1





        Perhaps use Path.Combine over that first string.Join, for cross-platform?

        – canton7
        Mar 22 at 8:41











      • @canton7: Thank you! Path.Combine is much better in the context

        – Dmitry Bychenko
        Mar 22 at 8:44











      • Also a very nice solution. More readable for me. :)

        – Christoph Brückmann
        Mar 22 at 8:58











      • I think this definitely wins the prize for readability

        – canton7
        Mar 22 at 9:40







      1




      1





      Perhaps use Path.Combine over that first string.Join, for cross-platform?

      – canton7
      Mar 22 at 8:41





      Perhaps use Path.Combine over that first string.Join, for cross-platform?

      – canton7
      Mar 22 at 8:41













      @canton7: Thank you! Path.Combine is much better in the context

      – Dmitry Bychenko
      Mar 22 at 8:44





      @canton7: Thank you! Path.Combine is much better in the context

      – Dmitry Bychenko
      Mar 22 at 8:44













      Also a very nice solution. More readable for me. :)

      – Christoph Brückmann
      Mar 22 at 8:58





      Also a very nice solution. More readable for me. :)

      – Christoph Brückmann
      Mar 22 at 8:58













      I think this definitely wins the prize for readability

      – canton7
      Mar 22 at 9:40





      I think this definitely wins the prize for readability

      – canton7
      Mar 22 at 9:40











      3














      You can go forward-only in one loop like this:



       var folder = "one.two.three";
      var newFolder = new StringBuilder();

      int index = -1;
      while (index + 1 < folder.Length)
      index = folder.IndexOf('.', index + 1);
      if (index < 0)
      newFolder.Append(folder);
      break;

      else
      newFolder.Append(folder, 0, index);
      newFolder.Append(Path.DirectorySeparatorChar);




      You can try it out here.






      share|improve this answer





























        3














        You can go forward-only in one loop like this:



         var folder = "one.two.three";
        var newFolder = new StringBuilder();

        int index = -1;
        while (index + 1 < folder.Length)
        index = folder.IndexOf('.', index + 1);
        if (index < 0)
        newFolder.Append(folder);
        break;

        else
        newFolder.Append(folder, 0, index);
        newFolder.Append(Path.DirectorySeparatorChar);




        You can try it out here.






        share|improve this answer



























          3












          3








          3







          You can go forward-only in one loop like this:



           var folder = "one.two.three";
          var newFolder = new StringBuilder();

          int index = -1;
          while (index + 1 < folder.Length)
          index = folder.IndexOf('.', index + 1);
          if (index < 0)
          newFolder.Append(folder);
          break;

          else
          newFolder.Append(folder, 0, index);
          newFolder.Append(Path.DirectorySeparatorChar);




          You can try it out here.






          share|improve this answer















          You can go forward-only in one loop like this:



           var folder = "one.two.three";
          var newFolder = new StringBuilder();

          int index = -1;
          while (index + 1 < folder.Length)
          index = folder.IndexOf('.', index + 1);
          if (index < 0)
          newFolder.Append(folder);
          break;

          else
          newFolder.Append(folder, 0, index);
          newFolder.Append(Path.DirectorySeparatorChar);




          You can try it out here.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 22 at 8:49

























          answered Mar 22 at 8:44









          SefeSefe

          10.9k52646




          10.9k52646





















              3














              Instead of splitting the string first, I find it more elegant to start with what you have and reduce it:



              var folder = "one.two.three";
              var newFolder = string.Empty;
              for (var f = folder; f.Any(); f = f.Remove(Math.Max(f.LastIndexOf('.'), 0)))
              newFolder = Path.Combine(f, newFolder);

              Console.WriteLine(newFolder);


              Output:



              oneone.twoone.two.three 





              share|improve this answer



























                3














                Instead of splitting the string first, I find it more elegant to start with what you have and reduce it:



                var folder = "one.two.three";
                var newFolder = string.Empty;
                for (var f = folder; f.Any(); f = f.Remove(Math.Max(f.LastIndexOf('.'), 0)))
                newFolder = Path.Combine(f, newFolder);

                Console.WriteLine(newFolder);


                Output:



                oneone.twoone.two.three 





                share|improve this answer

























                  3












                  3








                  3







                  Instead of splitting the string first, I find it more elegant to start with what you have and reduce it:



                  var folder = "one.two.three";
                  var newFolder = string.Empty;
                  for (var f = folder; f.Any(); f = f.Remove(Math.Max(f.LastIndexOf('.'), 0)))
                  newFolder = Path.Combine(f, newFolder);

                  Console.WriteLine(newFolder);


                  Output:



                  oneone.twoone.two.three 





                  share|improve this answer













                  Instead of splitting the string first, I find it more elegant to start with what you have and reduce it:



                  var folder = "one.two.three";
                  var newFolder = string.Empty;
                  for (var f = folder; f.Any(); f = f.Remove(Math.Max(f.LastIndexOf('.'), 0)))
                  newFolder = Path.Combine(f, newFolder);

                  Console.WriteLine(newFolder);


                  Output:



                  oneone.twoone.two.three 






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 22 at 16:50









                  sebrockmsebrockm

                  1,8251320




                  1,8251320



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55295571%2fbuilding-a-new-path-like-string-from-an-existing-one%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                      SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                      은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현